0

I'm working on a website http://www.imbeeld.nl with some js:

$(document).ready(function() {
  var personPosition = 0;

 function scrollToEl(el) {
  $('html, body, *').animate({scrollLeft: $(el).offset().left}, 1000);
  }

  $('#wrapper_h1').on('click', 'div.body_arrowr', function(e) {
  e.preventDefault();
  var nextPerson = $('#wrapper_h1 div.body').get(personPosition + 1);
  personPosition += 1;
  scrollToEl(nextPerson);
  });

  $('#wrapper_h1').on('click', 'div.body_arrowl', function(e) {
   e.preventDefault();
  var previousPerson = $('#wrapper_h1 div.body').get(personPosition - 1);
  personPosition -= 1;
  scrollToEl(previousPerson);
  });

$('.button, .menu_button, #back').on('click', function() {
scrollToEl('#' + $(this).data('target'));
});
}); 

The two arrows, left and right, navigate to the previous and the next div.body ('person' in the script). But when scrolling manually trough the site, the personPosition will not be changed. So clicking an arrow after scrolling will navigate to the next slide after the last one visited by an arrow.

How to include the scroll position when navigating with the arrows?

Erwin
  • 1

1 Answers1

0
$(document).keydown(function(e) {
    switch(e.which) {
        case 37: // left
           var nextPerson = $('#wrapper_h1 div.body').get(personPosition + 1);
           personPosition += 1;
           scrollToEl(nextPerson);
           break;

        case 39: // right
           var previousPerson = $('#wrapper_h1 div.body').get(personPosition - 1);
           personPosition -= 1;
           scrollToEl(previousPerson);
           break;

        default: return; // exit this handler for other keys
    }
    e.preventDefault(); // prevent the default action (scroll / move caret)
});

Code inspired by this answer

Community
  • 1
  • 1
curlybracket
  • 413
  • 2
  • 9