Ben Welch Ben Welch - 3 months ago 25
HTML Question

mousewheel and if statements jquery

What I'm trying to do is make it so when you try to scroll up or down it calls a function that changes the page. My body has

overflow:hidden
.

I'm using the jquery plugin called https://github.com/jquery/jquery-mousewheel'>mousewheel

This is my code:

$('#body').on('mousewheel', function(event) {

if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) {
//scroll down
if(document.getElementById('pgcount').innerHTML == 'Page 1') scrollDown(2);
if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollDown(3);
if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollDown(4);
if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollDown(5);
} else {
//scroll up
if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollUp(1);
if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollUp(2);
if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollUp(3);
if(document.getElementById('pgcount').innerHTML == 'Page 5') scrollUp(4);
}
//prevent page fom scrolling
return false;

});


For some reason it works when scrolling up but when you scroll down it goes straight to page 5 (the last one). When i added
console.log(document.getElementById('pgcount').innerHTML)
to each if statement for scrolling down it logged this:

Page 1
Page 2
Page 3
Page 4


I don't understand why it would work scrolling up but not down. I know that the function being called (scrollDown) isn't the problem as it works when called from the console.

Thanks in advance

Answer

Assuming the scrollDown() function alters the page value, the solution is pretty clear:

if(document.getElementById('pgcount').innerHTML == 'Page 1') scrollDown(2);
if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollDown(3);
if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollDown(4);
if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollDown(5);

If you're on page 1, the code calls scrollDown(2), moving you to page 2. Then the code immediately checks to see if you're on page 2, and if so it scrolls to page 3. The process repeats until you get to page 5.

Things would be a lot cleaner if you kept track of the page explicitly instead of looking at the page text. However the simplest thing to do with the code you have is add else:

if(document.getElementById('pgcount').innerHTML == 'Page 1') scrollDown(2);
else if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollDown(3);
else if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollDown(4);
else if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollDown(5);