Andy Nightingale Andy Nightingale - 3 months ago 17
jQuery Question

Using e.preventDefault(); to prevent clicking a link twice

I'm trying to close an off canvas navigation panel by clicking on a link in that panel. You can open/close the panel with a hamburger button and close it when you click anywhere on the page.

See: http://whyyouthinking.com/xindex.html#what

I got to the point where it was working but the hamburger had to be clicked twice to work again.

$(document).ready(function () {
"use strict";
$('.panel ul li a').on("click", function () {
$('.menu-link').removeClass("active");
$('.panel').animate({left: '-=250'});
});
});


I've got round that with:

$(document).ready(function () {
"use strict";
$('.panel ul li a').on("click", function () {
$('.menu-link').removeClass("active");
$('.panel').animate({left: '-=250'});
});
$('.panel ul li a').on('click', function(e) {
e.preventDefault();
$('.menu-link').click();
});
});


Now I have the problem that the e.preventDefault(); is also stopping my 'scrollto' function, when you click on a link in the panel. Is there a way of just targeting the .menu-link?

Answer

Here Scroll to event registered to "#menu" selector as well, so when ever user clicks on panel list anchor tag, its scrolling to target offset, as well as #menu target offset due to $('.menu-link').click();.

So restrict page scroll animation to #menu selector. A #menu selector conditional check added: if(target.selector != "#menu" && target.length).

/*Scroll to function*/
$(function() {
    "use strict";
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.selector != "#menu" && target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top - 60
                }, 1000);
                return false;
            }
        }
    });
});

It would be nice if you unregister event for #menu selector, check this: $('a[href*="#"]:not([href="#"]):not([href="#menu"])').click(function(e) {...}