Search This Blog

Wednesday 19 June 2013

Ignored powerful shortcuts of jQuery

Many developers ignore shortcuts and power of jQuery and I myself being a victim of some of the useful, handy but yet ignored shortcuts of jQuery. These are not some advance or complex shortcuts but I guess these are used a lot.

Consider, below jQuery code lines.
$("#elm").css("display", "none"); //Line 1
$("#elm").css("display", ""); //Line 2
$("#elm").html(""); //Line 3
Above code lines are very common but its unfortunate because some faster and more readable shortcuts available, yet ignored. Find below jQuery code lines that does the exactly same thing but these are more readable and fast.
$("#elm").hide(); //Line 1
$("#elm").show(); //Line 2
$("#elm").empty(); //Line 3
Related Post: There are many more examples which you can find in your code. For example, to add CSS Class to any element
$("#elm").prop("class", "cssClass");
where the better approach would be,
$("#elm").addClass("cssClass");
Another example is of setting height and width,
$("#elm").css("height", "100px"); //Line 1
$("#elm").css("width", "100px"); //Line 2
using in-built jQuery functions,
$("#elm").height(100); //Line 1
$("#elm").width(100); //Line 2
Another common situation is of toggling (show/hide) of element. For example,
if($("#elm").is(":visible")) 
$("#elm").css("display", "none");
else
$("#elm").css("display", "");
where the better approach is,
$("#elm").toggle();
You can find many such situation where in-built jQuery functions can be used. Hope you find this useful and if you are also ignoring these shortcuts, then you need to move on...

Feel free to contact me for any help related to jQuery, I will gladly help you.

No comments:

Post a Comment