Scroll to the next <div> when you press 'j'

I think you all saw this feature on facebook. When you click j, the scroll position advances to the next story, and when you click k, it scrolls to the previous story.

Now, if I have a lot of divs with a class .story(in the fragment they all have the same height, but in fact they will be different), how can I navigate through them (scroll through the next and previous .story) by clicking jand klike on facebook?

body{  
  background-color:#ecf0f1;
}

.story
{
  background-color: #fff;
  border-radius: 5px;
  height: 500px;
  margin: 20px auto;
  width: 70%;
}
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
Run code
+4
source share
2 answers

$(document).keypress(function(e){
  var forward;
  if (e.keyCode == 106) {
    forward = true;
  } else if (e.keyCode == 107) {
    forward = false;
  } else {
    return true;
  }
  
  if (!$(".story.current").length) {
    $(".story:first").addClass("current");
  }
  
  if ($(".story.current").length) {
    var current = $(".story.current");
    var next;
    if (forward) {
      next = current.next(".story")
    } else {
      next = current.prev(".story");
    }
    if (next.length) {
      current.removeClass("current");
      next.addClass("current");
    } else {
      alert("nope.");
    }
  }
  
  $("html, body").animate({ scrollTop: $(".current").offset().top }, 100);
});
body{  
  background-color:#ecf0f1;
}

.story
{
  background-color: #fff;
  border-radius: 5px;
  height: 500px;
  margin: 20px auto;
  width: 70%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="story">
  a
</div>
<div class="story">
  b
</div>
<div class="story">
  c
</div>
<div class="story">
  d
</div>
<div class="story">
  e
</div>
<div class="story">
  f
</div>
<div class="story">
  g
</div>
<div class="story">
  h
</div>
<div class="story">
  i
</div>
<div class="story">
  j
</div>
Run code
+4
source

, :

var $story = $('.story');

$(document).keyup(function(e) {
    var index;

    if (e.keyCode == 74) {
        index = $story.filter('.focused').index() + 1;
    }
    else if (e.keyCode == 75) {
        index = $story.filter('.focused').index() - 1;
    }

    if (index < $story.length && index >= 0) {
        $story.removeClass('focused').eq(index).addClass('focused');   
    }

    $("html, body").animate({ 
        scrollTop: $focused.offset().top 
    }, 200);
});

: http://jsfiddle.net/vfw15v7d/

0

All Articles