I know that JavaScript return false means prevent default event (like preventDefault() method).
#1
<a href="http://stackoverflow.com" onclick="return false;">click</a>
#2
<a id="a" href="http://stackoverflow.com">click</a>
<script>
document.getElementById('a').addEventListener('click', function(){ return false; }, false);
</script>
I wonder why just #1 prevent default event but not #2. Did I make some mistake?
Edit:
Sorry, I missed an id of anchor tag and third argument of code in #2. I added it but it’s still not working.
There are two problems with your second example:
You’re using
document.getElementByIdbut you’re giving a tagname. You can probably usedocument.getElementsByTagName(which returns aNodeListyou would then index into), or give the element anidattribute and usegetElementByIdto look it up.Your
addEventListenercall is missing the third argument, which is required. So:Regarding your question about
return false: If you’re using a browser that supportsaddEventListenerand you’re hooking up event handlers with it, no, you don’t usereturn falseto prevent the default action. Instead, you useevent#preventDefault. (You can also useevent#stopPropagationto stop the event bubbling, but DOM0’sreturn falsedoesn’t do that, so that’s just an extra bonus.)Also note that there are a lot of people using IE8 and earlier, which do not support
addEventListener(instead, they support Microsoft’s originalattachEvent; but not all versions supportpreventDefaultorstopPropagation).Somewhat off-topic: As you can see, handling events in a cross-browser way is a hassle. It’s one of the many hassles you can avoid by using a decent JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browser differences and provide lots of helpful utility functionality, so you can focus on what you’re actually trying to build (rather than worrying about how IE7 and earlier have a broken version of
getElementById).Examples:
jQuery: jQuery provides a
return falsefeature (although it’s different from the DOM0 one you’re talking about), and it also ensures thatevent#preventDefaultandevent#stopPropagationwork regardless of how the underlying browser handles events. So either of these work with jQuery:Prototype: Prototype provides the DOM standard event methods (even on browsers that don’t support them) as well as
event#stopwhich is just a combination of preventing the default and stopping propagation:Other libraries will offer similar functionality.