return false considered harmful in live

Neeraj Singh

Neeraj Singh

March 10, 2010

Checkout following jQuery code written with jQuery.1.4.2. What do you think will happen when first link is clicked.

1$("a:first").live("click", function () {
2  log("clicked once");
3  return false;
4});
5$("a:first").live("click", function () {
6  log("clicked twice");
7  return false;
8});

I was expecting that I would see both the messages. However jQuery only invokes the very first message.

return false does two things. It stops the default behavior which is go and fetch the link mentioned in the href of the anchor tags. Also it stops the event from bubbling up. Since live method relies on event bubbling, it makes sense that second message does not appear.

Fix is simple. Just block the default action but let the event bubble up.

1$("a:first").live("click", function (e) {
2  log("clicked once");
3  e.preventDefault();
4});
5$("a:first").live("click", function (e) {
6  log("clicked twice");
7  e.preventDefault();
8});

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.