Please note, this is a STATIC archive of website www.htmlgoodies.com from 16 Nov 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
Wednesday, November 16, 2022

Top 10 jQuery Tips and Tricks

jQuery is a simple, light-weight, open source, cross browser JavaScript library that simplifies event handling, animations and developing Ajax-enabled web applications and promotes rapid application development. In this article we will discuss some useful tips and tricks in jQuery.

jQuery Development Pre-requisites

To get started with jQuery you should have the following installed in your system:

  • Visual Studio 2008
  • Visual Studio 2008 SP1
  • jQuery Library
  • Visual Studio 2008 jQuery Plug-in
  • You can download the jQuery library here.

    Alternatively, you can just install Visual Studio 2010. This comes with the jQuery library by default.

    The jQuery Tips and Tricks

    We will now discuss some tips and tricks to use jQuery to its fullest potential. In this section we will discuss a series of such tips.

    Disabling Right Mouse Click

    If you are to disable right click on your web browser, you can use the following piece of code:

    $(document).ready(function(){
    $(document).bind(“contextmenu”,function(e){
    return false;
    });
    });

    Determine Browser

    Suppose you were to determine the browser type of the browser currently in use. You can use the following piece of code to do this:

    $(document).ready(function() {
    // If the browser type if Mozilla Firefox
    if ($.browser.mozilla && $.browser.version >= "1.8" ){ 
    // some code
    }
    // If the browser type is Opera
    if( $.browser.opera)
    {
    // some code
    }
    // If the web browser type is Safari
    if( $.browser.safari )
    {
    // some code
    }
    // If the web browser type is Chrome
    if( $.browser.chrome)
    {
    // some code
    }
    // If the web browser type is Internet Explorer
    if ($.browser.msie && $.browser.version <= 6 )
    {
    // some code
    }
    //If the web browser type is Internet Explorer 6 and above
    if ($.browser.msie && $.browser.version > 6)
    {
    // some code
    }
    });
    

    Detect Current Mouse Coordinates

    Now, suppose you need to detect the current mouse coordinates in the web browser in use. To do this, you can write the following piece of code:

    $(document).ready(function() {
    $().mousemove(function(e)
    {
    $('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
    });
    <DIV id=MouseCoordinates></DIV>
    });
    

    Check if an Element Exists

    To check whether an element exists, you can write the following code:

    if ($("#someElement").length)
    { 
    //The DOM element exists
    }
    else
    {
    //The DOM element doesn't exist
    }
    

    Check if an Element Is Visible

    To check whether an element is visible, you can use the following piece of code:

    if($(element).is(":visible") == "true")
    { 
    //The DOM element is visible
    }
    else
    {
    //The DOM element is invisible
    }
    

    Set a Timer

    The following piece of code can be used to set a timer using jQuery:

    $(document).ready(function()
    {
    window.setTimeout(function()
    {
    // some code
    }, 500);
    });
    

    jQuery’s Chaining Feature

    Chaining is a great feature in jQuery that allows you to chain method calls. Here is an example:

    $('sampleElement').removeClass('classToBeRemoved').addClass('classToBeAdded');
    

    You can also use jQuery to store state information of DOM elements in your web page. It contains the data() method that you can use to store state information of the DOM elements in key/value pairs. Here is an example:

    $('#someElement').data('currentState', 'off');
    

    Lazy Loading

    Lazy loading is a great feature in jQuery that ebales you to load only the content that is needed. To use this, you should incorporate the jquery.lazyload.js script file as shown below:

    <script src="jquery.js" type="text/javascript"></script>
    <script src="jquery.dimensions.js" type="text/javascript"></script>
    <script src="jquery.lazyload.js" type="text/javascript"></script>
    Next, you can use the lazyload() method as shown below:
    $("imageObject").lazyload();
    

    Preloading Images

    Preloading images in a web page improves performance. This can particularly be useful while an animation is in progress- your web page need not wait for the image to be loaded. You can use jQuery to preload images with simple code. Here is an example:

    jQuery.preloadImagesInWebPage = function() {
    for(var ctr = 0; ctr<arguments.length; ctr++)
    {
    jQuery("<img>").attr("src", arguments[ctr]);
    }
    }
    To use the above method, you can use the following piece of code:
    $.preloadImages("image1.gif", "image2.gif", "image3.gif");
    To check whether an image has been loaded, you can use the following piece of code:
    $('#imageObject').attr('src', 'image1.gif').load(function() {
    alert('The image has been loaded…');
    });
    

    jQuery Cloning

    jQuery supports cloning – you can use the clone() method to create a clone of any DOM element in your web page. Here is an example:

    var cloneObject = $(‘#divObject’).clone();

    The $(document).ready function is called during page render, i.e., while the objects are still being downloaded in the web browser. To reduce CPU utilization while a page is being loaded, you can bind your jQuery functions in the $(window).load event. Note that this event is fired after all objects have been downloaded successfully. This would improve the application performance to a considerable extent as the page load time would be minimized. Other common ways to improve jQuery performance are by compressing the scripts and limiting DOM manipulation as much as possible.

    Consider the following piece of code that appends a DOM element inside a loop:

    for (var ctr=0; ctr<=rows.length; ctr++)
    {
    $('#tableObject').append('<tr><td>'+rows[ctr]+'</td></tr>');
    }
    The above code can be replaced by a more efficient piece of code to minimize DOM manipulation and hence improve application performance as shown below:
    var str = '';
    for (var x=0; x<=rows.length; x++)
    {
    str += '<tr><td>'+rows[x]+'</td></tr>';
    }
    $('#tableObject').append(str);
    

    References

    Here’s a list of links to some useful references on jQuery:

  • jQuery Documentation
  • 20 Tips and Tricks for jQuery Programmers
  • Improve Your jQuery
  • 10 Ways to Increase Your jQuery Performance
  • jQuery Performance Rules
  • Summary

    jQuery is a fast, light-weight JavaScript library that is widely popular and has simplified the way you write JavaScript code these days. In this article we discussed some useful tips and tricks in jQuery.

    Happy reading!

    Joydip Kanjilal
    Joydip Kanjilal
    A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at https://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

    Popular Articles

    Featured