3

I have two events: one that is onclick which scrolls to certain div when I click on the menu and the other one in onscroll which "highlight" the menu item when the scroll is near to the div.

My question is: how can I "disallow" the execution of one event while the other is executing.

Here is my code:

function goToByScroll(id){ var value = $(id).offset().top; var scrl = value - 154; $('html,body').animate({ scrollTop: scrl}, 'slow'); } //scroll menu control $("#menu-home ul li a").click(function(e) { e.preventDefault(); $("#menu-home ul li a").removeClass('menu-home-active'); $(this).addClass('menu-home-active'); goToByScroll($(this).attr("href")); }); //scroll bar control $(window).scroll(function() { var scrv = $(this).scrollTop(); var allmenu = $("#menu-home ul li a"); if(scrv == 0){ allmenu.removeClass('menu-home-active'); $('#menu-div1').addClass('menu-home-active'); } if(scrv > 458 && scrv < 478){ allmenu.removeClass('menu-home-active'); $('#menu-div2').addClass('menu-home-active'); } if(scrv > 989 && scrv < 1009){ allmenu.removeClass('menu-home-active'); $('#menu-div3').addClass('menu-home-active'); } if(scrv >= 1324){ allmenu.removeClass('menu-home-active'); $('#menu-div4').addClass('menu-home-active'); } }); 

Thanks

2 Answers 2

3

First of; the click-event isn't firing when the scroll-event is (or the other way around). When you get to the scroll event, the click-event is already finished.

What you should probably do is set a variable on the click event like this:

function goToByScroll(id) { window.isAutoScrolling = true; var value = $(id).offset().top; var scrl = value - 154; $('html,body').animate({scrollTop: scrl}, 'slow', goToByScrollCompleted); } function goToByScrollCompleted() { window.isAutoScrolling = false; } 

Then you add to the start of the scroll-event this:

if(window.isAutoScrolling) return; 

Also, as for registering the goToByScrollCompleted, this can probably be done in many ways, however, since I don't know how you do the scrolling I can't say.

Sign up to request clarification or add additional context in comments.

1 Comment

I think I am putting the variable to complete the scroll in a wrong place. I have updated the code with the function that automate the scroll. Thanks
1

You can have global boolean variable lock, check wheter it's false, if yes set it to true and execute your function. Then reset it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.