and-k
and-k

Reputation: 607

"Disallow" execution of an event when another one is executing jQuery

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

Upvotes: 3

Views: 112

Answers (2)

Alxandr
Alxandr

Reputation: 12423

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.

Upvotes: 3

Michal Klouda
Michal Klouda

Reputation: 14521

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.

Upvotes: 1

Related Questions