I am having trouble with multiple clicks being registered in jQuery when only one element has been clicked. I have read some other threads on Stack Overflow to try and work it out but I reckon it is the code I have written. The HTML code is not valid, but that is caused by some HTML 5 and the use of YouTube embed code. Nothing that affects the click.
The jQuery, triggered on document.ready
function setupHorzNav(portalWidth) {
$('.next, .prev').each(function() {
$(this).click(function(e) {
var target = $(this).attr('href');
initiateScroll(target);
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});
});
function initiateScroll(target) {
var position = $(target).offset();
$('html, body').animate({
scrollLeft: position.left
}, 500);
}
}
Example HTML
<nav class="prev-next">
<a href="#countdown-wrapper" class="prev">Prev</a>
<a href="#signup-wrapper" class="next">Next</a>
</nav>
In Firefox one click can log a "Click!" 16 times! Chrome only sees one, but both browsers have shown problems with the above code.
Have I written the code wrongly or is there a bug?
-- Some extra info ------------------------------------------
setupHorzNav is called by another function in my code. I have tested this and have confirmed it is only called once on initial load.
if ( portalWidth >= 1248 ) {
wrapperWidth = newWidth * 4;
setupHorzNav(newWidth);
}
else
{
wrapperWidth = '100%';
}
There are mutiple instances of nav 'prev-next'. All target different anchors. All are within the same html page.
<nav class="prev-next">
<a href="#video-wrapper" class="prev">Prev</a>
</nav>
setupHorzNavfrom and the code surrounding<nav class="prev-next">?eachin this scenario, just use:$('.next, .prev').click(function (e) { //... });. And you don't need to use all three ofe.stopPropagation();,e.preventDefault();andreturn false;.return false;automatically does thepreventDefaultandstopPropagation. Those are useful if you only want to do one of them, or want to execute it sooner thanreturn falsebecause of possible problems in your codeconsole.logright at the start of yoursetupHorzNavfunction and check how many times it is getting called.