简体   繁体   中英

scroll to particular div using jquery in all devices and browsers

I have problem in scroll to particular div (id wise),it's works well in desktop but not working mobile devices below (768 px).

I used this code for scroll but it's not working well in mobile.

// Scroll based on devices width
if ($( window ).width() <= 768 ){
    $('body').animate({ 
        scrollTop: $("#current-job").offset().top 
    }, 1000);
}
else {
     $('html, body').animate({
        scrollTop: $("#current-job").offset().top
    }, 1000);
}

Would you please give me the solution for the same ?

Thanks in advance

Ok so there is an issue where mobile webkit just doesn't do that. you COULD build your own animate function and rock an update of some low level prop but let's cheat a bit here.

Scrolling the body is an issue but scrolling a div is not. have a look at this pen.

https://codepen.io/infn8/pen/BYGvjz

This takes a single div, #body-wrapper , as an immediate child of the body and makes it the new window using these styles:

#body-wrapper{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow-y:auto;
  -webkit-overflow-scrolling: touch;
}

Then you can animate the scrolling on that. the -webkit-overflow-scrolling: touch; is what gives the ability to flick and scroll a bunch.

then you add the following JS

jQuery(document).ready(function($) {
    $(".scroll-bottom").click(function(event) {
        $('#body-wrapper').animate({scrollTop: $(".scroll-top").position().top}, 'fast');
    });
    $(".scroll-top").click(function(event) {
        $('#body-wrapper').animate({scrollTop: $(".scroll-bottom").position().top}, 'fast');
    });
});

Notice the swapping of .offset() for .position() this is important because with the overflow in the div the offset becomes incorrect. It's also important because the item you take the position of must have #body-wrapper as its offset parent ( more info here ) or the calculation will be wrong.

I have made my example scrollable with two buttons and a different layout than yours so it is a reduced test case scenario and nothing else is in the way. this way you can study this and extact the core concepts into your application.

a quick conversion of your original would look like this:

$('#body-wrapper').animate({ 
    scrollTop: $("#current-job").position().top 
}, 1000);

hopefully that helps

The one you have in the else block is fine on its own. Just reduce it all to:

$('html, body').animate({
    scrollTop: $("#current-job").offset().top
}, 1000);

and it will work. The key is animating both the html and body elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM