I suggest you take the addEventListener
/attachEvent
approach instead of using inline scripts. They are much cleaner and upholds separation of concerns. Here's a simple patch which makes it crossbrowser.
//assuming NS is an object, your namespace
NS.addEL = (function binding(){
if(window.addEventListener){
return function addEventListener(el, ev, handler){
el.addEventListener(ev, handler);
}
} else if(window.attachEvent) {
return function attachEvent(el, ev, handler){
el.attachEvent('on' + ev, handler);
}
} else {
return function(){/*not supported for some reason*/}
}
}());
Using the said patch, you can have a cleaner HTML. Using #
is a safeguard that prevents the link to point to nowhere, but the page jumps up. This will be your "last line of defense" from going somewhere.
<a href="#" id="link" title="Add link">Add Link</a>
And the JS that goes with it, we use our patch. Our main defense against the link moving the page away is event.preventDefault
.
Another way is returning false after the entire operation. This prevents eveything, and I mean everything that happens after it. It's link calling event.preventDefault()
and event.stopPropagation
. You may be doing some delegation, so this might not be advisable.
I suggest using href="#"
and event.preventDefault
to stop the link from going somewhere.
var link = document.getElementById('link');
NS.addEL(link,'click',function(event){
//prevent the link from moving us away
event.preventDefault();
window.open('https://www.example.com/add?url='+encodeURIComponent(window.location)+'&text='+encodeURIComponent(document.title))
//one way to prevent default, but stops propagation and everything else
return false;
});
If this is some tracker code, which displays nothing on the opened window, I suggest you route this to an iframe instead.