June 12, 2013

jquery click(), live() and on()

Adam’s Question:

just interested to know which of – Click(), Live() and On() is currently the preferred method to catch a user mouse click?

I assume live() is out as this I believe scans to much of the DOM.

thankyou

From jquery docs:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers. Users of older versions of jQuery should use
.delegate() in preference to .live(). This method provides a means to
attach delegated event handlers to the document element of a page,
which simplifies the use of event handlers when content is dynamically
added to a page. See the discussion of direct versus delegated events
in the .on() method for more information.

The .on() method attaches event handlers to the currently selected set
of elements in the jQuery object. As of jQuery 1.7, the .on() method
provides all functionality required for attaching event handlers.

For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

TLDR: Always use on() , never use live()

live() and .bind() methods are deprecated. live() has also been removed where as other two are two totally two different types of event handlers.

  1. .click() is a standard event handler

    .click(function() {
        //Applies to DOM already present
    });
    
  2. .on() is used when you require event delegation. This replaced traditional bind() and delegate()

    .on('click', function() {
            //Delegates to each element is DOM as it manipulated or generated
    });
    

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!