Most useful JQuery function


For the record, JQuery is awesome!!

So much more powerful and flexible than Javascript alone. Below are what I feel are the most useful JQuery functions and explanations to their use:

.on()
The “on” function is brilliant.  It encompasses all the event listeners like “click”, “change”, “mouseover” etc into a single function. But why use this instead of the classing “.click” function? The reason is that “.on” can be applied to a parent tag and then told which sub-tags to function on, an example would be:

        $(‘#products_list’).on(‘click’,’a’,function(){});

Here I have basically allocated the “click” event listener to ALL A-tags within the #products_list tag.

I hear you say: “this isn’t any different to just doing $(‘#products_list a’).click(function(){});”!!!

Well the beauty is that the “.on()” function works on DOM-tree manipulated structures too where as the “.click()” (and others) do not.  This means that I can create as many A-tags under the #products_list tag as I want using JQuery DOM-tree manipulation (e.g. the “.append()” function) and the “.on()” event listener would apply to these new A-tags also.  With the old-style “.click()” function, you would have to recreate a new listener each time you created an A-tag as once these listeners are initialised, they remain in-place with the specific tags and not inherited to new tags.

.find()
This function can be used in 2 different instances, you can either look for a specific tag which is within a tag, e.g.:

        HTML:
       

                     
    • Test

           

To find the A-tag in this HTML from the UL you would simply use:

        $(‘ul’).find(‘a’);

From this you can run whatever functions you wish on the A-tag. e.g.:

        $(‘ul’).find(‘a’).text(‘New Test’);

This will change the contents of the A-tag from “Test” to “New Test”.

The “.find()” function can also be used to find multiple tags which can then be inspected individually using the “.each()” function. For example:

        HTML:
       

                     
    • Test 1

                     
    • Test 2

                     
    • Test 3

           

To get all the A-tags you would again use:

        $(‘ul’).find(‘a’);

But then to identify each individually you would use:

        $(‘ul’).find(‘a’).each();

Within the “.each()” function you can then place your own function to manipulate each A-tag accordingly:

        $(‘ul’).find(‘a’).each(function() {
                $(this).addClass(‘bold’);
        });

This would add the class “bold” to all A-tags within the UL-tag.

Don't forget to read more interesting web development and web design articles in our Blog!

livechat