This function is quite quick and efficient in counting and returning the number of linebreaks in a string:
The following code mimics the php include_once functionality in that it loads / includes a certain script resource only if it has not been loaded before.
Many experienced programmers try to impose classical OO structures on JavaScript. Although it's possible JavaScript wasn't specifically designed for this. Using prototypes inheritance can be accomplished much simpler:
Often when you want to display content from remote sites or applications seamlessley on your own site, an iframe is the quickest and easiest solution. Here's how you open one using JavaScript:
To clear the text, textareas, passwords, selects, radios and checkboxes, but leave for instance hidden inputs (and any other form-elements not specified in the code below) alone you can safely use the following jQuery code. You can easily add additional field types to clear those also.
If your using JavaScript in a browser it can be as simple as this:
You can use the same jQuery traversal and selection methods for XML that you use for (X)HTML. this makes it very easy to parse an XML file and process it's contents if you already know jQuery.
Here's a quick example of an rss parsing script.
The XML file of course needs to be on the same domain or retrieved via a simple serverside proxy script, because of cross site scripting restrictions in JavaScript:
This is the simplest and fastest way of finding the maximum value in a JavaScript array:
To see whether an attribute on an html or xml element is actually defined / present, you can do the following:
This code exemplifies how you quickly retrieve the position of your mouse using jQuery
This simple bit of jQuery code allows you to quickly detect and hide all elements containing a specifed text value on a page:
the following shows how you can quickly see what the index of an element is, using the prevAll() method
Yhe following snippet shows one way you can quickly switch the source for your screen stylesheet with jQuery:
HTML5 has introduced the new canvas element, which allows us to generate graphics dynamically with the help of Javascript. To draw on a canvas element we must first specify a 'context' in which to work. This is done using the getContext method. Below a quick example:
One of the things that jQuery makes so much easier in javascript is detecting keyboard events crossbrowser. Here's a simple example detecting the cursor / arrow keys up down left and right:
This is how you use the back and go method of the window's history property to imitate the back button, next button or even go back or forth a few entries in the browsers history.
This little script allows you to sort items in a list or any similar dom-based structure using jQuery.
The following jQuery plugin allows you to handle forms submits via ajax rather than via page (re) loading. Havent built in support for checkboxes and radio yet but that shouldn't be too hard if needed.
The folowing javascript places Ajax calls in an array and goes through them one by one making sure they get called successively and only one at the time, allowing you to controll the order in which your calls reach / are processed by the server.
In this example the $.post() method calls made presume the jQuery library is loaded. To adapt to other library just use another ajax call method.
The following code checks whether we are in a frame and also makes sure the code get's exectued only if the frame is the second frame in the parents frameset:
It's always quite handy to register something general for handling errors occuring in your script when using Ajax in jQuery:
Somewhere in your jQuey based Ajax handling scripts register a general error handler like so:
You use the window.open method to open a new window in javaScript. The arguments to this method are as follows:
You can easily check whether the page you're on is in a frameset by comparing the top and self properties like so:
Works in all major browsers.
Here's how you can enforce a redirect to a https ssl address when a page is accessed via http. Is ofcourse only effrective if they have JavaScript turned on. Works in frames as well
To match special characters in JavaScript regular expressions you can either use their predefined escape values (if they excist) or use their unicode representations.
\uhhhh matches the Unicode character with four characters of hexadecimal code hhhh.
Or you can use the live method to bind the keyup handler to future additions to the DOM:
you can use the following function to check whether any JavaScript value is a valid number :
In OOP the singleton is basically a class which restricts it's instantiation to one object. This is useful for when only a single object is needed to maintain a certain functionality or global state available throughout a complex system.
In JavaScript the singleton serves first and foremost as a namespace provider to isolate implementation code from the global namespace and providing a single point of access for functionalities.
The JavaScript Singleton can take several different forms each providing different possibilities and limitations. Below are examples of the two most commonly used singleton structures.
In it's simplest form the JavaScript is simply an object literal grouping together related methods and properties:
The fact that you can use CSS pseudo selectors to select elements in jQuery makes it much easier to find the element or input with focus inside a document. You can simply use the :focus pseudo selector. This works on all major browsers except ofcourse IE6.
The window.onerror event provides a very simple way of supressing javascript errors. This does off course not solve any javascript error caused problem by itself, but it does provide a useful tool for supressing the symptoms while you're busy debugging errors in you javascript code.
The event fires whenever an javascript error occurs.
This javascript bookmark / favourite function will work on Mozilla or IE browsers. For web kit based (Safari / Chrome) handle it accordingly or hide it as you like.
Use this function to sort elements inside an unordered html list <ul>
source: http://www.go4expert.com/forums/showthread.php?t=1947
To retrieve a select's selected option value you can use the jquery val() function but if you specifically the text node's contents of the selected option you can use something like the following:
This simple jquery plugin adds the option to get / set the url of the background image of the jQuery selected elements. The main point of this is just simplifying the extraction of the background image's - location in clean url-format from the element's css properties, so it can be used for other images. This is done by a simple regular expression.
There's a lot of vertical align javascript solutions around all using roughly the same mechanisms to vertically align html elements inside their containers. A good example of javascript stepping in where CSS seems to fail miserably. It seems strange that css fails to provide clear specifications for this essential alignment behavior in html lay-out.
Luckily it's quite easy to do with jQuery.
This works well for elements that are block displayed :
This is just one way you can do this with the this placeholder :
This jquery code loops through all checkboxes in the dom and sets their checked attribute to the opposite of what it currently is.
The following design pattern was taken from Mike Alsup's article on the website learning jquery and serves as a handy starting point for scripting jquery plugins.
You can check if jQuery has been loaded just as you would for any other Javascript object:
The following jQuery code will load the google Analytics code on dom ready thus preventing any slowdown in the loading of the page. replace the the UA-xxxxxx-x bit with your your google analytics account id:
To scroll to top of the page with jQuery use the following:
If you need a modal box quickly and have jQuery in place:
you can just adjust and paste the following line of code in any eventhandler to quickly flash a message in a modal box for a short period of time on the screen. Adjust the script to your needs:
This simple regex based function returns a js object built from the value name pairs in the get string allowing you to access them in a manner similar to the PHP $_GET global.
If necessary adjust the regular expression to your needs, but this should fit most general purposes:
The below is a quick example of how to initiate swfobject - a script to to embed flash objects in html - on an html page.
If the browser supports it you can use location.replace to replace the current page in the browsers history with another page - so that clicking back will skip the redirection page. It's good to add a location.href redirect for browsers that don't support it.
This jquery plugin takes a container element and wraps in an extra container and creates two links -- one for scrolling it's content to the left and the other for scrolling it to the right.
Download it here or grab the code below
The script has been tested on Safari, IE and FF .
It does require all scrollable items to share the same width -this is something I may change in a later version
Several carousel options are exposed for controlling automated scrolling , lay-out etc.
This can be seen the carousel below that was created with the following call:
You can use a construct similar to the following to reload a page with a small change to the url string using javascript.
To change xml to a string or the other way around you can use the following methods depending on the browser being used:
-
The javascript string object lacks a native trim method for removing leading and trailing spaces. Here's a function that does the job:
This simple javascript is used to add a few social media links to your webpage. You can add any social media you like by extending the socialMedia object that contains the data.
This uses jQuery for selecting the element and appending content to it, but you could easily use document.getElementById('elementId').innerHTML = 'bla' instead if you want to include the media links without the jQuery.
To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.
I use this a lot nowadays for keeping clickhandlers organized neatly in a single object where I can quickly find them if neccesary.
If you use this all you have to do is give elements the classname '.linked' and create a corresponding function in the linkhandler lookup table
This is a quick lightweight modal window script with background overlay. It's been tested on Safari 2 and 3, FF 2 and 3 and IE6-8. Needs jQuery to be included
This is triggered as soon as the dom is ready for manipulation
The CDATA tags need to be included for the page with javascript to validate as XHTML. They also should be commented out for older browser who don't understand CDATA tags:
You can use jQuery to access elements in another frame by accessing the jQuery object in that frame. You should always check if it exists (/ has been loaded yet) first.
This fires after everthing is fully loaded. Use window.onload cause document.onload doesn't work xbrowser
serialize javascript object to string
the frameset can be set dynamically.
Opens an OS printer dialog. Javascript print link example:
Although browser detection is going out of fashion fast, I still use it sometimes to quickly deal with bugs in certain browsers .
This is an example of how you can use the browser object in jQuery to target specific browsers and their versions. The code in the below conditional is only executed when Internet Explorer 6 loads the page:
This adds shuffle method to array prototype to randomize the order of it's elements
Creates guid-like string
Two simple javascript functions for getting and setting cookie values
This little javascript function will return an array of document elements that have the class name specified
(or false if none are found).Â
The sort of thing that comes standard with any js library but is allways handy to have around when you have to do without.
returns true if value 'needle' is in array haystack and false if it isn't
where 11 dictates that the random number will fall between 0-10. To increase the range to, say, 100, simply change 11 to 101 instead.
To detect Internet explorer:
For images you can use the js Image object's methods:
Very lightweight and efficient tab script with fade in / fade out effect.
The following script goes in the head section:
Tested to work on IE5+, FireFox and Safari.
replace the frame[1] with the identifier of your frame.
Will keep on checking till it finds the element in the addressed frame and only execute your code when it's there. Can be used for instance to check if the document object in the addressed frame is ready etc.
Javascript refresh link - refreshes the page just like the refresh button on the browser:
This will make an element with id footer stick to the bottom of the window, but only if the document body height is less than the window height. If it isn't it 'll just follow the normal document flow.
No margin,border or padding should be set on the element, only on its children if need be, for this to work properly:
Execute the function, and what is in between the curly-brackets, for each of the DOM elements that matches the selector. The keyword 'this' refers to the current element the loop is dealing with.
The function specified receives an iterator as argument by default, represented in this example here as 'i'.
The javascript string object lacks a native leading / trailing white-space stripping method. The following function does the job.