Reputation: 2608
I am trying to make jquery scroll down of just the section's height (which is responsive) when the user presses page down :
<section class="intro viewportheight_min" id="intro">
...
</section>
<section id="page2">
...
</section>
<section c id="page3">
...
</section>
css for full height sections :
body, html, .container, section {
height: 100%;
margin:0;
}
Here is the js :
var ar=new Array(33,34,35,36,37,38,39,40);
$(document).keydown(function(e) {
var key = e.which;
// PgUp(33), PgDn(34), End(35), Home(36), Left(37), Up(38), Right(39), Down(40)
if( key==33 ) {
$(document).scrollTop( $(document).scrollTop() - $(window).height() );
}
if( key==34 ) {
$(document).scrollTop( $(document).scrollTop() + $(window).height() );
}
return true;
});
But this doesn't work, it goes at almost at the bottom of the last section.
Upvotes: 2
Views: 986
Reputation: 3804
Adapt your code using this logic. Works on all elements even if they don't have the same height
var positionMap = {};
$('section').each(function(){
var $this = $(this);
positionMap.push({ height: $this.outerHeight(true), position: $this.offset() });
}
$(document).keydown(function(e) {
var key = e.which;
//the current scroll position
var currentPos = $('body').scrollTop();
if( key==33 ) {
//Find next section position
for (var i=0; i<positionMap.length; i++)
{
var e = positionMap[i];
//found the pre
if (e.position.top > currentPos){
destination = e.position.top;
break;
}
}
}
else if( key==34 ) {
//Find previous section position
for (var i=0; i<positionMap.length; i++)
{
var e = positionMap[i];
//found the pre
if (e.position.top + e.height >= currentPos){
destination = e.position.top;
break;
}
}
}
$('body').scrollTop(destination);
return true;
});
Upvotes: 4
Reputation: 14025
Not tested but you could try and adapt something like :
$(document).keydown(function(e) {
var key = e.which;
//Find first visible section
$el = $('section').filter(':visible').first();
if( key==33 ) {
//Find next section position
var offset = $el.next().offset();
$(document).scrollTop( offset.top );
}
if( key==34 ) {
//Find previous section position
var offset = $el.prev().offset();
$(document).scrollTop( offset.top );
}
return true;
});
Also I assume that 33 and 34 are the right keycode fr page up and down.
Upvotes: 1