ania_piszko ania_piszko - 1 month ago 7
Javascript Question

jQUery --> After window resize scroll to section does not work as expected

After window resize my scroll function does not work as I described below (description shows how I want it to work):


  1. I do window resize.

  2. After window resize when I click the given menu item the window should scroll to...

  3. corresponding to that menu item section offset().top-45 for max-width:480px (first breakpoint)

  4. corresponding to that menu item section offset().top-90px for min-width 481px (second breakpoint)



https://jsfiddle.net/d1abevro/1/

It only works as expected for a given breakpoint without window resize (onload).

function displaymenu() {


if ($(window).width() <= 480) {

$('.c-main-menu ul').css({display: 'none'});

$(document).on("click", "a.c-main-menu__link", function(event){
event.preventDefault();
$('html,body').animate({
scrollTop: $($.attr(this, 'href')).offset().top-56
}, 800);
$('.c-main-menu ul').slideToggle();
});
$('.c-nav .menu-trigger').click(function() {
$('.c-nav .c-main-menu ul').slideToggle();
});

} else {

$('.c-main-menu ul').css({display: 'block'});
$(document).on("click", "a.c-main-menu__link", function(event){
event.preventDefault();
$('html,body').animate({
scrollTop: $($.attr(this, 'href')).offset().top-90
}, 800);
});
}
}

Answer Source

That is caused because after each resize you append a new event. You should kill the old event an create a new one in order to prevent conflict with the old event. To get this approach the best way is to adding a namespace for your event, for example:

$(document).on("click.menuLinkEvent",".my_links", function(){});

And before adding the new event kill any old event it using unbind method and passing the event with the namespace:

$(document).unbind("click.menuLinkEvent");

Also looks like you understand correctly that the event will be appended each time after resize so you added a setTimeout function, but forgot to add a time, so however it will fire inmediately.

I made some changes to your fiddler. Let me know if it works as you expect