0

I have one anchor element in my page

<a href="..." id="page">Click</a>

I know in jQuery we have so many ways of binding events to element like (bind, live, delegate, on).

FYI:

http://blog.tivix.com/2012/06/29/jquery-event-binding-methods/

Currently using jquery1.8.3.min.js. I want to know which one is standard and efficient event registration model in jQuery?

Currently I am doing it like this:

      $("#page").click(function(){
................................

    });

Can I change to bind like below code:

$("#page").bind("click",clickFunc);

function clickFunc()
{
..........
}

Which one is best practice to register the event in jQuery 1.8 ?

1
  • 5
    As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. Commented Jan 2, 2014 at 15:47

3 Answers 3

1

The best way is the way one can understand what's written and the one that works.
The smart way is to use what's suggested to use, in this case the .on() method:

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 help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

The how-to way depends if you need to delegate your event/s to dynamically generated elements or not.

$('.child').on( 'click', function() { /* ... */ });
$('#parent').on( 'click', ".dyn-gen-child", function() { /* ... */ });
Sign up to request clarification or add additional context in comments.

Comments

1

.on is the standard method:

$("#page").on("click", function() {
    .......
});

If the p element is generated dynamically, you'll have to do:

$(document).on("click", "#page", function() {
    .......
});

3 Comments

As a side note -performance wise- instead of document use the first non-dynamically-generated parent element as selector.
Yes. Good point. Then it doesn't have to search as far through the DOM.
Exactly, due to event bubbling pretty expensive if document is the last horizon.
1

Actually, after jQuery 1.7, on is the preferred way to bind events rather than bind. So I prefer on API.

And then:

click(function(){})

is just the shortcut of

on('click',function(){})

Internally, they are actually the same -- when the on param is event, handler, but on is more general because it can do more than simple onClick(example:event delegation) see:link

so I recommend on

1 Comment

wasn't it from v. 1.7?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.