return false not preventing href action

J

james.kingston

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

Richard Cornford

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.

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top