Sunday, January 23, 2011

Jquery Best Practices and Tips.


1.  How To Check If An Element contains a certain class or element with has():

//jQuery 1.4.* includes support for the has method.

$("input").has(".mail").addClass("mail_icon");


2. How To Detect Any Browser:

Detect Safari (if( $.browser.safari)),
Detect IE6 and over (if ($.browser.msie && $.browser.version > 6 )),
Detect IE6 and below (if ($.browser.msie && $.browser.version <= 6 )),
Detect FireFox 2 and above (if ($.browser.mozilla && $.browser.version >= '1.8' ))

3. Always start the selection  From an #id

The fastest selector in jQuery is the ID selector ($('#someid')).
This is because it maps directly to a native JavaScript method, getElementById().

Read More




4. How to find out the index of an element in an unordered set

$("ul > li").click(function () {
    var index = $(this).prevAll().length;
});

5.How to Bind a function to an event:

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

6.Use $(window).load aheadof $(document).ready

There is a temptation among jQuery developers to hook everything into the $(document).ready pseudo event.
Although $(document).ready is useful, it occurs during page render while objects are still downloading.It can stall your page sometimes.
You can reduce CPU utilization during the page load by binding your jQuery functions to the $(window).load event,
which occurs after all objects called by the HTML (including <iframe> content) have downloaded.

7. Effective Usage of Event Delegation in JavaScript

Every event (e.g. click, mouseover, etc.) in JavaScript “bubbles” up the DOM tree to parent elements.
This is incredibly useful when we want many elements (nodes) to call the same function.
Instead of binding an event listener function to many nodes which is very inefficient, instead , you can bind it once to their parent,
and have it figure out which node triggered the event.

For example, say we are developing a large form with many inputs, and want to toggle a class name when selected.
A binding like this is inefficient:

$('#myList li).bind('click', function(){
$(this).addClass('clicked');
// do stuff
});
Instead, we should listen for the click event at the parent level:

$('#myList).bind('click', function(e){
var target = e.target, // e.target grabs the node that triggered the event.
$target = $(target);  // wraps the node in a jQuery object
if (target.nodeName === 'LI') {
$target.addClass('clicked');
// do stuff
}
});
The parent node acts as a dispatcher and can then do work based on what target element triggered the event.
If you find yourself binding one event listener to many elements, you are doing something wrong (and slow).


8. How to hide an element that contains text of a certain value:

   $("p.value:contains('thetextvalue')").hide();
 


 





No comments:

Post a Comment

subversion video