Reputation: 705
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.
Upvotes: 0
Views: 187
Reputation: 60577
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);
}
Upvotes: 1
Reputation: 14279
Are you getting any errors in your console? I suspect that you are getting an error on the following line, which breaks the JS execution, which is causes the stopPropigation
to not be executed. The error might be on this line:
$(e.path[0].hash.replace('#', '.'))[0].scrollIntoView()
When you index the array with [0]
, you get the native JS object - not a jQuery object. Therefore, when you try to call the jQuery function .scrollIntoView()
you should be getting an error. You can either wrap that indexed expression in a jQuery object or else use the .eq()
function, which indexes an array and returns the result as a jQuery object.
$($(e.path[0].hash.replace('#', '.'))[0]).scrollIntoView()
//or
$(e.path[0].hash.replace('#', '.')).eq(0).scrollIntoView()
Personally, I prefer the second method since it looks cleaner.
Upvotes: 1
Reputation: 179
Try this
function showFoo(e) {
e.stopPropagation();
e.preventDefault();
console.log('event', e);
//$(e.path[0].hash.replace('#', '.'))[0].scrollIntoView()
}
var links = document.getElementsByTagName('a')
console.log(links)
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', showFoo )
}
<a href="#test"> See console output </a>
Upvotes: 1