469,923 Members | 1,856 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,923 developers. It's quick & easy.

return false not preventing href action

I've read that one must return false from an onclick handler attached
to an anchor if we wanted to prevent the browser from following the
href. In a greasemonkey script I'm hacking together with duct tape and
chicken wire the links that I'm creating follow the hrefs, killing the
associated action. To get around this, I'm assigning the URL which I
need in the logMe function to a made up attribute, rather than use
newlink.href as I do below.

In newlink below, my browser (Firefox) will follow the href despite my
returning false. What did I do wrong? Thanks

for (linkIndex = 0; linkIndex < doclinks.snapshotLength; linkIndex++)
{
var origlink = doclinks.snapshotItem(linkIndex);
if (origlink.href.match(myRE))
{
newlink = document.createElement('a');
newlink.innerHTML = " [ EXPAND ] ";
newlink.id = preamble + ":" + linkIndex;
newlink.href = origlink.href;
newlink.addEventListener('click', function(event){ logMe(event);
return false; }, false);
origlink.parentNode.insertBefore(newlink,origlink. nextSibling);
}
}

Sep 24 '05 #1
1 2077
ja************@gmail.com wrote:
I've read that one must return false from an onclick handler
attached to an anchor if we wanted to prevent the browser
from following the href.
That is true if the handler is assigned to the - onclick - property of
the elements.

<snip> newlink.addEventListener('click', function(event){ logMe(event);

<snip>

This is not assigning the handler to the - onclick - property of the
elements. It is assigning an event listener to the element using the W3C
Events DOM standard method. To cancel the default action (the navigation
to the HREF) from an event listener you call the - preventDefault -
method of the event object.

You would probably be better off assigning the function to - onclick -
property of the element, as that is much more cross-browser and just
returning false form that handler is reliable/sufficient:-

newlink.onclick = function(ev){
logMe((ev || window.event));
return false;
};

Assuming the intention is to only assign one event handler.

Though using an inner function may not be the best idea.

Richard.
Sep 25 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Colin Hale | last post: by
1 post views Thread by mailpitches | last post: by
5 posts views Thread by GiJeet | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.