

JQuery Events: Stop (Mis)Using Return False - vilda
http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

======
blantonl
I'll stand up and raise my hand and state "I do this often." I'll also say
that this article has me scheduling some code reviews this week of my own work
to find out where I'm doing this.

And, this is a well written article - especially since it points out actual
examples of _where_ things could go horribly wrong on a page with jquery
implementation and _why_ they could go wrong. That alone could possibly save
me hours of searching stackoverflow for reasons why my jquery events aren't
firing etc.

------
edanm
Brilliant article.

A great explanation of a pretty technical point most people gloss over. I for
one had to learn the lessons of this article the hard way and figure them out
for myself. I wish I had read this article before I started using javascript
heavily.

------
MichaelGG
I'm not very well versed with JavaScript/jQuery, so perhaps my thinking here
is completely off.

Is it often the case that you want to wire up a click handler to link, but
still want to follow the href? If not, why doesn't jQuery just automatically
prevent navigation for links when handling the click event? Then for the few
cases (confirming navigation, perhaps tracking user actions?) the programmer
could explicitly indicate the continue through with navigation.

Having to write preventDefault() in each handler seems like unnecessary noise,
doesn't it?

~~~
fooandbarify
One counterargument might be that it is unhelpful to prevent default event
behaviour depending on its type or target. Events normally bubble - that is
the expected behaviour. Clicks are just another event.

In life, rules need exceptions. In programming, it is usually nicer when there
are as few as possible.

EDIT: If you desire to preventDefault on multiple handlers and you don't want
to type it out every time you can simply add a line like

    
    
      $("a").click(function(e){e.preventDefault()});
    

to your document and stop click event bubbling for every link.

~~~
pilif
don't do that on IE where there are potentially a lot of <a>-tags. IE behaves
really, really badly once a selector matches a large amount of elements (there
must be something O(n^2) going on somehwere).

This is what delegate() was invented for.

    
    
        $(document).delegate('a.nodefault', 'click', function(e){
          e.preventDefault();
        }
    

I'm using a .nodefault class selector such that it applies only to links
marked with class="nodefault" - you might want to have links that should work
normally.

If you're using HTML5, using a data-yourapp-nodefault=true attribute might be
even better as you shouldn't overload classes.

Incidentally, returning false; in a directly bound handler (which is was the
original article was talking about) prevents exactly this suggestion here from
working as the delegated handler on document would never see the click.

------
lindvall
I wish the title wasn't so much about "Stop doing ___" but the contents of the
article are good for people to be aware of.

These are little details of how systems work that are just brushed over too
often but are important to get right.

~~~
kragen
At least it's not "considered harmful".

------
pippy
Sadly it's another IE6 hangover.

event.preventDefault() does not work in IE6, you have to use event.returnValue
= false;. To not break standard compliant browsers you have to have
if(event.preventDefault) event.preventDefault();, but by then you have three
lines doing what one could do, you give up and use return false;. (and not use
child click events).

Fortunately with IE6 usage under 5% now, I'm sure your boss wouldn't notice
it.

~~~
Encosia
jQuery's normalized event object handles that issue automatically when you
call _its_ preventDefault method().

------
purephase
I'm with blantonl. I do this more often than I should (and I know better).

I've actually been struggling with a click event handler not firing and this
article may have pointed me in the right direction.

Thanks for the link.

------
mcdaid
Great article, particularly like the Top, Bottom or Somewhere in the Middle
section. I had never considered how the position of e.preventDefault() would
make a difference.

------
robryan
I think for me I've always just returned false unless their was some specific
reason not to, which hasn't come up overly often. But yeah it could be
something that is confusing when it comes back to reviewing code down the
track.

~~~
pilif
the problem is that if there's just one "return false" somwhere in your app,
then you make it impossible to react to the same event somehwere else.

live() and delegate() stop working too.

Once your application gets big enough, finding that one return false can be
really painful, especially as browsers don't really help with their debug
tools to show you what handlers are bound to which events of which elements (I
know that there's some event handler debugging support, but it doesn't play
well with jquery)

------
qntm
This may sound like a stupid question, but if you don't want the browser to
follow a link when somebody clicks it, why not just leave off the href
attribute?

~~~
JonnieCache
Well, firstly a link tag with an empty href is semantically meaningless, and
it probably doesn't validate either.

More importantly this is part of a common pattern for progressive enhancement.
You create all your links with normal href attributes that point to real
pages. If the browser doesn't have javascript enabled (eg. the googlebot) then
navigation works as normal.

Then to enable your ajax navigation, you add an event handler to the links
that pulls the href attribute out and retrieves the content at that url via
ajax. You have your server notice that the request is an ajax one and only
send back the content without the layout, which the js then uses to update the
page. Obviously the browser must be prevented from following the link in the
normal way.

Bingo, AJAX navigation without _any_ extra markup, and with a flawless
fallback.

~~~
kragen
<a name=""> has been legal since before HTML had veersion numbers.

