0

I have a navbar which navigates to some block. When I click several times on button , after scrolling me to correct div, when I try to scroll up by myself , the scroll event form navigation bar scrolls me to the div as much time as I have clicked to nav item.

   function goToByScroll(id) {
        closeSidebar();
        const elem = $("body").find(`[data-el=${id}]`);
        $('html, body').animate({
            scrollTop: $(elem).offset().top
        }, 600);
        return false;
    }
  $("#mySidenav > a, #mySidenavMob > a, a").click(function (e) {
        // e.preventDefault();
        const dataAtrr = $(this).attr("data-id");
        if (dataAtrr) goToByScroll(dataAtrr);
    });

How should I avoid that ?

Sunstrike527
  • 515
  • 1
  • 4
  • 17
  • you should set a flag that animation in progress and check it before `closeSidebar()` and return immediately if that is true, if its false, then set it to true. Then set it to false inside a callback you can pass in animate method which will be called when [animation is complete](https://api.jquery.com/animate/). – Mat J Jun 11 '21 at 05:52
  • @MatJ no need for a flag, jquery already has it builtin: `if ($("body").is(":animated")) return;` (or, perhaps better, cancel the previous animation with `.finish()`) – freedomn-m Jun 11 '21 at 07:12
  • @freedomn-m, never knew. thanks – Mat J Jun 11 '21 at 07:19
  • @MatJ no worries, we work with what we know – freedomn-m Jun 11 '21 at 07:22
  • thanks guys really if ($("body").is(":animated")) return; worked – Sunstrike527 Jun 15 '21 at 03:55

1 Answers1

0

one of decisioun was to add timeout for me but I'm not sure that it is correct way

 function goToByScroll(id, link) {
        closeSidebar();
        link.css("pointer-events", "none");
        setTimeout(() => {
            link.css("pointer-events", "all");
        }, 650)
        const elem = $("body").find(`[data-el=${id}]`);
        $('html, body').animate({
            scrollTop: $(elem).offset().top
        }, 600);
        return false;
    }
Sunstrike527
  • 515
  • 1
  • 4
  • 17
  • [jquery 'animate'](https://api.jquery.com/animate/) has a callback `complete` for just this scenario - add your pointer-events all to the callback of the animate function. – freedomn-m Jun 11 '21 at 07:15
  • Also note that you're only disabling the one link that caused the first animation. Given your event handler target `$("#mySidenav > a, #mySidenavMob > a, a")` there's probably more than one link that could start the `goToByScroll`, but you only disable the *one* that initiated it. If you were to go down this route rather than `.is(":animated")` you should do `$("#mySidenav > a, #mySidenavMob > a, a").css("pointer-events", "none")` (etc) – freedomn-m Jun 11 '21 at 07:17