Magnus Ihle Magnus Ihle - 16 days ago 5
CSS Question

jQuery 100% vertical scroll (slide scrolling)

I know there are many great plugins for this purpose, but i feel like this is something i want to use alot, so i want to see how it's done! I know you can do it this way:

html:

<div id="section1">
<div id="section2">


css:

#section1{
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
}

#section2{
height: 100%;
width: 100%;
position: absolute;
top: 100%;
left: 0;
}

#section1:active{
position: fixed;
}

#section2:active{
position: fixed;
}


jQuery:

$(".wrapper").on('mousewheel DOMMouseScroll', function (event) {
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
$('.slide-1').addClass('active');
} else {
$('.slide-2').addClass('active');
}
});


I want to learn how you do it the best way. Im sorry about the code it was just something I wrote quick.

Answer

This is actually most typically done with a delta counter. You're going to need a library like jQuery mousewheel. Then you'll have an event that you can listen to called "mousewheel". Once you have that, the basic logic would look like this (scroll in the red window below):

var deltaCounter = 0,
	oldDelta = 0,
	scrollDirection = 0,
	threshold = 250;
$("html").on('mousewheel', function(e) {
	e.preventDefault();
	deltaCounter += e.deltaY;
	if (Math.abs(deltaCounter) >= threshold) {
		deltaCounter = 0;
		if (scrollDirection === 0) {
			next();
		} else {
			prev();
		}
	}
	if (oldDelta < deltaCounter) {
		scrollDirection = 1;
	} else {
		scrollDirection = 0;
	}
	oldDelta = deltaCounter;
});

function next(){
	console.log("NEXT PAGE");
}

function prev(){
	console.log("PREV PAGE");
}
body{
  background-color:rgba(255,200,200,0.3);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>

Once you have this, you can apply whatever you want to happen in a "next page" and "prev page" situation. Adjusting the threshold will determine how much scrolling is needed between "pages".

Comments