By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,842 Members | 2,368 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,842 IT Pros & Developers. It's quick & easy.

return false not preventing href action

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.