Javascript Reference

Javascript Count linebreaks

This function is quite quick and efficient in counting and returning the number of linebreaks in a string:

Javascript Include once method for JavaScript

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.

Javascript Prototype inheritance example

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:

Javascript Open an iframe and set source with JavaScript

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:

jQuery Clear form with jQuery

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.

Javascript Strip HTML tags with JavaScript

If your using JavaScript in a browser it can be as simple as this:

jQuery Parse RSS XML with jQuery

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:

Javascript Find max value in an JavaScript array

This is the simplest and fastest way of finding the maximum value in a JavaScript array:

jQuery Check if an attribute exists with jQuery attr

To see whether an attribute on an html or xml element is actually defined / present, you can do the following:

jQuery get mouse coordinates using jQuery

This code exemplifies how you quickly retrieve the position of your mouse using jQuery

jQuery Hide all elements containing a certain text value

This simple bit of jQuery code allows you to quickly detect and hide all elements containing a specifed text value on a page:

jQuery Find index of element relative to parent

the following shows how you can quickly see what the index of an element is, using the prevAll() method

jQuery Switch css stylesheet with jQuery

Yhe following snippet shows one way you can quickly switch the source for your screen stylesheet with jQuery:

jQuery plugin patterns jQuery

Below are some very useful design patterns for coding jQuery plugins.

Javascript Canvas getContext

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:

jQuery Detect cursor key events

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:

Javascript history back and history go

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.

jQuery Sort list elements using jQuery

This little script allows you to sort items in a list or any similar dom-based structure using jQuery.

jQuery minimalist ajax form plugin

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.

Javascript simple Ajax queuing script

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.

jQuery quick ajaxloader animation

ajaxAnim=function(close){ if (close){ setTimeout($.fn.openOverlay.closeOverlay,1000); //$.fn.openOverlay.closeOverlay(); return; } if($('#loaderImage').length){ ajaxAnim(1); ajaxAnim(0); } $('body').append('
'); $('#loaderImage').openOverlay(); }

Javascript Detect in what frame a script is executed.

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:

jQuery Register general ajax or getJSON error handler

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:

Javascript window.open method

You use the window.open method to open a new window in javaScript. The arguments to this method are as follows:

Javascript check for frames

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.

Javascript detect or enforce http or https with JavaScript

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

Javascript matching special characters in JavaScript regular expressions

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.

jQuery detect enter key in jQuery

Or you can use the live method to bind the keyup handler to future additions to the DOM:

Javascript simple isnumber function in JS

you can use the following function to check whether any JavaScript value is a valid number :

Javascript Singleton examples in JavaScript

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:

jQuery find input with focus

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.

Javascript window onerror event to supress javascript errors

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.

Javascript Add bookmark / favourite link

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.

Javascript Sorting an unordered list

Use this function to sort elements inside an unordered html list <ul>

source: http://www.go4expert.com/forums/showthread.php?t=1947

jQuery get selected option's text value from a select

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:

jQuery Background image url getter setter

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.

jQuery vertical align plugin

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 :

jQuery supplying context to handler lookup table in jquery

This is just one way you can do this with the this placeholder :

Javascript toggle all checkboxes checked or unchecked

This jquery code loops through all checkboxes in the dom and sets their checked attribute to the opposite of what it currently is.

jQuery The openOverlay simple overlay and modal jQuery plugin

//application example: $('#simpleExample4').click(function(){ $(this).openOverlay({sColor:'#ffffff',iOpacity:60}); })

jQuery plugin design pattern

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.

Javascript Check if jQuery is loaded / defined on the page

You can check if jQuery has been loaded just as you would for any other Javascript object:

jQuery Insert google analytics with jquery

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:

jQuery Scroll to top with animate function

To scroll to top of the page with jQuery use the following:

jQuery Quick and dirty modal box using jQuery

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:

Javascript Retrieve get name-value pairs from url

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:

Javascript swfobject - quick example for copy/paste

The below is a quick example of how to initiate swfobject - a script to to embed flash objects in html - on an html page.

Javascript location.replace and location.href redirect

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.

jQuery Image carousel plugin for jquery

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:

Javascript Use regular expression to alter name / value in url

You can use a construct similar to the following to reload a page with a small change to the url string using javascript.

Javascript XML to string and string to XML in Javascript

To change xml to a string or the other way around you can use the following methods depending on the browser being used:
-

Javascript Javascript trim function

The javascript string object lacks a native trim method for removing leading and trailing spaces. Here's a function that does the job:

jQuery Social media icon script

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.

Javascript Copy or clone javascript array / object

To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.

jQuery Eventhandler lookup table design pattern

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

jQuery Simple modal window in jquery

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

jQuery declare dom ready handlers

This is triggered as soon as the dom is ready for manipulation

Javascript Correct way to include Javascript in XHTML

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:

jQuery Access element in a sibling frame

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.

Javascript document onload or window onload event

This fires after everthing is fully loaded. Use window.onload cause document.onload doesn't work xbrowser

Javascript toJson function

serialize javascript object to string

Javascript resize frameset

the frameset can be set dynamically.

Javascript Javascript print link

Opens an OS printer dialog. Javascript print link example:

jQuery Target specific browser with jquery browser object

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:

Javascript Array shuffle function

This adds shuffle method to array prototype to randomize the order of it's elements

 

Javascript Create guid in Javascript

Creates guid-like string

Javascript Get cookie and set cookie

Two simple javascript functions for getting and setting cookie values

Javascript Get elements by className

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.

Javascript Array search

returns true if value 'needle' is in array haystack and false if it isn't

Javascript Generating random integer with Math.random()

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.

Javascript Browser detection

To detect Internet explorer:

Javascript Frames

frames['frameName'].document.innerHTML

Javascript XML Object to string

var string = obj.xml; alert(string);

Javascript Javascript string to XML object:

Javascript Javascript check if file excists

For images you can use the js Image object's methods:

jQuery Tiny jQuery tab script

Very lightweight and efficient tab script with fade in / fade out effect.

The following script goes in the head section:

Javascript Retrieve other frame's scroll offset.

Tested to work on IE5+, FireFox and Safari.

replace the frame[1] with the identifier of your frame.

Javascript Repeatedly check if an object in a sibling frame is loaded.

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 javascript refresh link

Javascript refresh link - refreshes the page just like the refresh button on the browser:

jQuery jQuery sticky footer

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.

If instead you want to make the footer always stick to the bottom of the window (comparable to css statement 'position:fixed; bottom:0' ) use the second example.

No margin,border or padding should be set on the element, only on its children if need be, for this to work properly:

Javascript Javascript mouseover image swap

jQuery jQuery .each loop example

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'.

Javascript Javascript trim function

The javascript string object lacks a native leading / trailing white-space stripping method. The following function does the job.

jQuery jQuery check if dom element exists

if ( $("#myid").length > 0 ) { //do something }
[x]