Friday, 25 January 2013

jQuery Tutorials: Tips and Tricks for Web Developers

jQuery Tutorials: Tips and Tricks for Web Developers

jQuery has made web designing and development very easy. In this jQuery tutorial, some basic points about jQuery are listed like shorthand for jQuery and importance of CDN (Content Delivery Network). We have also covered some cool jQuery tips and tricks which are commonly used while web designing and development like how to disable right click on web browser in a single line of jQuery script, how to get mouse position using jQuery script, how to find which mouse button was clicked and how to efficiently use jQuery selectors? Every web designer and developer should know these basic tips and tricks of jQuery. These are very easy to learn and grasp and also time saving which reduces human efforts.

1. Use shorthand for $(document).ready()

We can write jQuery code like this:

$(document).ready(function()
{
  //Your jQuery code goes here.
})

But there is a shorthand available for above code. This can be rewritten as

$(function ()
{
   //Your jQuery code goes here.
});

2. Always load jQuery framework from Google, Microsoft or jQuery CDN(Content Delivery Network).

CDN provides several advantages:

1. You always use the latest jQuery framework.
2. It reduces the load from your server.
3. It saves bandwidth. jQuery framework will load faster from these CDN.
4. The most important benefit is, it will be cached if the user has visited any site which is using jQuery framework from any of these CDN.

Code to load jQuery Framework from Google CDN

<script  type="text/javascript"
    src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>

Code to load jQuery Framework from Microsoft CDN

<script  type="text/javascript"
    src="
http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

Code to load jQuery Framework from jQuery Site(EdgeCast CDN)<script  type="text/javascript"
    src="
http://code.jquery.com/jquery-1.4.2.min.js">
</script>

3. How to disable right click using jQuery?

You can find many java script code snippets to disable right click. But jQuery makes our life easy. Below jQuery code disables the right click of mouse.

Method 1:

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

Method 2:

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        e.preventDefault();
    });
});

4. How to get mouse cursor position using jQuery?

$(document).ready(function(){
  $(document).mousemove(function(e){
     $('#spnCursor').html("X Axis : " + e.pageX + " Y Axis : " + e.pageY);
  });
});

When the DOM is ready, we listen for mousemove event. Whenever user moves the mouse then this event gets called and we bind the pageX and pageY property to the span element.

5. How to find which mouse button is clicked using jQuery?

If you need to determine which mouse button (Left, Middle or Right) was clicked. jQuery provides mousedown() event, using which we can check which mouse button is clicked. For key or button events, event attribute indicates the specific button or key that was pressed. event.which will give 1, 2 or 3 for left, middle and right mouse buttons respectively. The advantage of using event.which is that it eliminates cross browser compatibility.

$(document).ready(function() {
$('#btnClick').mousedown(function(event){
    switch (event.which) {
        case 1:
            alert('Left mouse button pressed');
            break;
        case 2:
            alert('Middle mouse button pressed');
            break;
        case 3:
            alert('Right mouse button pressed');
            break;
        default:
           break;
    }
});
});

6. How to use jQuery selectors efficiently?

It is pretty important to understand how to write efficient element selection statement. One has to be very careful while jquery selector statement. Below are some tips on how to use your jQuery selectors efficiently.

A. Always try to use ID as selector

You can use ID as selector in jQuery. See below jQuery code.

$("#elmID");

When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element.

When Classes are used as selector then jQuery has to do DOM traversal.So when DOM traversal is performed via jQuery takes more time to select elements. In terms of speed and performance, it is best practice to use IDs as selector.

B. Use class selector with tags

You can use CSS classes as selector. For example, to select elements with "myCSSClass" following jQuery code can be used.

$(".myCSSClass");

As said earlier, when classes are used DOM traversal happens. But there could be a situation where you need to use classes as selector. For better performance, you can use tag name with the class name. See below

$("div.myCSSClass");

Above jQuery code, restricts the search element specific to DIV elements only.

C. Keep your selector simple, don't make it complex

Avoid complex selectors. You should use make your selectors simple, unless required.
$("body .main p#myID em");

Instead of using such a complex selector, we can simplify it. See below:

$("p#myID em");

D. Don't use your selector repeatedly

See below jQuery code. The selectors are used thrice for 3 different operation.

$("#myID").css("color", "red");
$("#myID").css("font", "Arial");
$("#myID").text("Error occurred!");

The problem with above code is, jQuery has to traverse 3 times as there are 3 different statements.But this can be combined into a single statement.

$("p").css({ "color": "red", "font": "Arial"}).text("Error occurred!");
 
E. Know how your selectors are executed

Do you know how the selectors are executed? Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".

$("p#elmID .myCssClass");

4 comments:

  1. Congratulations! This is the best thing, Thank you so much for taking the time to share this exciting information.
    Bblawyers

    ReplyDelete
  2. It may looks simple, but it is very effective while implementation.

    Thanks a ton

    ReplyDelete
  3. I liked it, I wanted to implement right click disable on my blog, thanks for your help.

    ReplyDelete