Javascript Bind function to mouse wheel

755 views Asked by At

I have a single page website that uses internal anchors to give the illusion of multiple pages. I have written a javascript function that reads the mousewheel up/down from the user and that based on that, sends the user to the anchor above/below the current page they are. The function is working properly as described however the mousewheel is so sensitive that the slightest move will fire multiple mousewheel events and send the user multiple pages up/down instead of just one.

I need a way to limit how many times my mousewheel function can be executed so that the user only moves one page in either direction on the mousewheel regardless of fast/slow the mousewheel was used. My javascript is below.

<script>
$(document).ready(function(){
$("#main").bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
var currentPage = $(".active").attr('href');
switch(currentPage){
case "#publications":
    window.location = $("#menu-item-290 a").attr('href');
    break;
case "#branding":
    window.location = $("#menu-item-106 a").attr('href');
    break;
case "#website-development":
    window.location = $("#menu-item-110 a").attr('href');
    break;
case "#about-us":
    window.location = $("#menu-item-109 a").attr('href');
    break;
case "#contact":
    window.location = $("#menu-item-108 a").attr('href');
    break;
}

}
else {
var currentPage = $(".active").attr('href');
switch(currentPage){
case "#home":
    window.location = $("#menu-item-106 a").attr('href');
    break;
case "#publications":
    window.location = $("#menu-item-110 a").attr('href');
    break;
case "#branding":
    window.location = $("#menu-item-109 a").attr('href');
    break;
case "#website-development":
    window.location = $("#menu-item-108 a").attr('href');
    break;
case "#about-us":
    window.location = $("#menu-item-107 a").attr('href');
    break;
}

}
 });
});
</script>
2

There are 2 answers

1
Twoquestions On

Instead of going to a part of the page directly on mousewheel, you could set a very short setTimeout (like 50 ms or so) to go where you want to go, like thus:

case "#home":
    var timeout = null;
    timeout = setTimeout('window.location = $("#menu-item-106 a").attr("href")', 50);
    break;

That way, if there's 20 mousewheel events in quick succession, you only fire the action you want to do once.

0
Heretic Monkey On

You're already querying wheelDelta, so why not use that? According to MSDN it "indicates the distance that the wheel has rotated, expressed in multiples of 120". So, just change your if statement to be something like >= 360 and add an if to your else for negative numbers.