return false considered harmful in live

Neeraj Singh

By Neeraj Singh

on 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});

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.