Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

.click vs. bind

Which is right? I see both and not sure which one to use or what the difference is between

$('#learnmore a').click( function(event) { event.preventDefault(); });

or

$('#learnmore a').bind('click', function(event) { event.preventDefault();

7 Answers

Looks like .on is the better, more current method. It also allows you to access new elements that are dynamically created, where as with .bind the element must already exist.

http://api.jquery.com/bind/

"As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. "

All should work if what you're attaching the click or bind method was in the dom when the jquery loaded. If it's something that got added to the dom after, via ajax or something, than click or bind wouldn't work, but on still would.

Hi Eric, there is no big difference. The .click seems to be a shortband for the .bind version. The only difference is that .bind can handle more than one event.

.on is definitely better. I using click:

.on("click", function() {

});

if bind, just replace "click" with "bind"

I agree, .on is generally better than .click

Thanks so much. But all technically should work? Nothing is deprecated.

Correct-- .bind is not deprecated - you can still use this "older" method