jQuery, one of these framework, changed the way web developers used to think and work to create rich functionality in there web pages.
Why should you choose jQuery?
While attempting to add dynamic functionality to your page, you would normally be selecting an element or group of element and then performing some operations like showing or hiding them, changing content or style.
Let’s consider an example where you want alternate highlighting for the table row. This can be easily done using jquery in following manner
jquery primarily focuses on performing various kinds off operations on page elements. For these operations, you select elements using css “selectors” (selectors specifies an element or group of element based on their attribute or place in DOM).
One major advantage of using jquery is that you can be sure that your code will execute identical in all browser.
In addition to this jquery developers have also provided simple means to extend the library functionality to build plugins or custom functionality.
Selectors and jQuery
CSS “selectors” is a way by which you can refer to page elements. This selection of group is on the basis of element’s attributes or position in DOM.
Will refer to all the links within the paragraph element. This css selector can also be used with jquery to perform some operations on this selection.
To select elements on page using jquery we use a very simple syntax
So our earlier example will look as follows
The $() method of jquery returns an array of DOM elements based on the selector provided in form of object. These objects have many methods associated to it for performing different activities.
This programming concept is called “wrapper” cause it wraps the matching element
Let us consider an example where you would like to fade out elements within our previously used selector. You would do that in following manner
Here fadeout() is one of the methods provided by jquery. You can also chain these function calls or for simplicity these jquery commands to execute many actions. Example
The selector used can be any kind off selector like id, class, attribute based selector.
Window.onload = function()
However drawback of his traditional method is that your code will be executed only after all components of that document are loaded, that includes images as well. This causes unnecessary delay even if this code’s execution is not dependent on these components presence.
A better approach to this would be to execute code as soon as browser has converted html code into a DOM structure. Jquery lets you do this using document.ready() function
Syntax for this looks like
//Code to execute
Document.ready also has a shorthand form which is more easy to use. That is as follows
//Code to execute});