Hillboy Hillboy - 7 months ago 18
Javascript Question

Javascript: Link tag 'a' stopPropagation() doesn't work in firefox

Using this:

function showFoo(e) {
$(e.path[0].hash.replace('#', '.'))[0].scrollIntoView()
e.cancelBubble = true;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
e.cancel = true;
return false;
}
var links = this.getElementsByTagName('a')
console.log(links)
for (var i = 0; i < links.length; i++) {
links[i].onclick = showFoo
}


Doesn't work on Firefox. But works on Chrome fine

Answer

I can't locate path as a valid MouseEvent property in any specification so I'm not sure it's even a standard property, but in either case Firefox does not support it, and you are likely receiving an error in your console.

However, you can just replace e.path[0] with the standard e.currentTarget. Better still you can replace the nasty .onclick with an addEventListener call, and then you can just use stopPropagation and preventDefault.

function showFoo(e) {
    $(e.currentTarget.hash.replace('#', '.'))[0].scrollIntoView()
    //e.cancelBubble = true;
    e.stopPropagation();
    e.preventDefault();
    //e.returnValue = false;
    //e.cancel = true;
    //return false;
}
var links = this.getElementsByTagName('a')
console.log(links)
for (var i = 0; i < links.length; i++) {
    //links[i].onclick = showFoo
    links[i].addEventListener('click', showFoo);
}