0

The problem is that my scroll function is not scrolling properly on different screen resolutions. Problem is coming from the offset. Is there any way to have offset in percents? I've tried -10% for example but it didn't worked.

$(".scrollto_home").click(function (event) {
    event.preventDefault();

    var defaultAnchorOffset = 0;

    var anchor = $('#home').attr('data-attr-scroll');

    var anchorOffset = $('#home').attr('data-scroll-offset');
    if (!anchorOffset)
        anchorOffset = defaultAnchorOffset;
    $('html,body').animate({
        scrollTop: $('#home').offset().top - 100 - anchorOffset
    }, 500);
});

The problem is that the scroll is going too far when going up on smaller resolutions that 1920x1080

Miyagi
  • 127
  • 8
  • Get a percentage of the screen size and then subtract it. To get literally the screen: `screen.height` to get the browser height: `window.innerHeight` but you might want to refer to this [article](https://stackoverflow.com/a/3333336/10315665). Or did I get your question wrong? – Elias Jan 22 '19 at 09:56
  • You get it right sir! I have a problem with calculating it and putting it into the script, tried many times – Miyagi Jan 22 '19 at 09:59

2 Answers2

0

You may try this way. Using timeout function

setTimeout(function(){
   $('html body').animate({
     scrollTop: $('#home')[0].scrollHeight
         },400);
},600);
  • But this doesn't solve the problem. The problem is that the scroll is going too far when going up on smaller resolutions that 1920x1080 – Miyagi Jan 22 '19 at 09:55
  • generally it scroll with your screen height. Then you need to define your screen size as you want to scroll – sabbir chowdury Jan 22 '19 at 10:15
0

So let's say you want to scroll 10% (of the screen height) below/above the anchor. You simply set the offset like:

let percentage = 10;
let offset = window.innerHeight / 100 * percentage;

and then add or subtract that offset depending if you want to scroll above or below it.

To get good browser compatibility when getting the screen height, refer to this.

Note: I'm not that used to jQuery so tell me if I'm missing something

Note2: If you're having problems with your jQuery, please consider creating a working JsFiddle so I can test out stuff ^^ :)

Elias
  • 3,592
  • 2
  • 19
  • 42