Search code examples
javascripthammer.js

how to scroll 50% of viewport height in window.innerheight


thats my full js code:

//init hammer function
var element=document.getElementById('pinwall-grid');
var hammertime=Hammer(element).on("drag", function(event) {
  direction=event.gesture.direction;
  if(direction == 'left')
  {
    var $meN=$('.pinwall-grid .ctrl a.next');

    if(!$meN.hasClass("nextD"))
    {
      $meN.trigger('click');
    }

    console.log('left');
  }
  else if(direction == 'right')
  {
    var $meP=$('.pinwall-grid .ctrl a.prev');

    if(!$meP.hasClass("prevD"))
    {
      $meP.trigger('click');
    }

    console.log('right');
  }
  else if(direction == 'up')
  {
    window.scroll({
      top: (window.innerHeight/2),
      left: 0,
      behavior: 'smooth'
    });

    console.log('down')
  }
  else if(direction == 'down')
  {
    window.scroll({
      top: (window.innerHeight/ -2),
      left: 0,
      behavior: 'smooth'
    });

    console.log('up')
  }

  event.gesture.stopDetect();
});

The issue here is that when you swipe up or down, it scrolls only 1 time but when i add a static value like -300 instead of ( window.innerHeight / -2 ), it works perfectly.

Any Idea what can i use instead of ( window.innerHeight / 2 ) to scroll 50vh every time you swipe up or down.

Note: I added the console.log to check if its reading the code every time you swipe down or up, and it is.

I guess its a measurement issue.

Check http://86.62.248.112/en/ (the Latest news Slider on mobile) to see what i'm talking about


Solution

  • window.scroll scrolls the document to a specified position. Once there, repeating the same scroll request should have no effect.

    window.scrollBy scrolls by a specified amount. The end position is relative to the start position and repeating the call should continue scrolling (if the document is big enough).

    I assume that "add a static value to the scroll position" used in a call to window.scroll meant you updated the scroll-to position - with result that the the document scrolled by the amount added.

    Try using window.scrollBy.