jQuery scoll to # on page with spacing

Hi,

I’'m trying to scroll to a specific element on a page on desktop, mobile and tablets.

I have this code:

jQuery(document).ready(function(){
jQuery('html, body').animate({
        scrollTop: jQuery('#scrollhash').offset().top }, 'slow');
});

<div class="scrollhash"></div>

The trouble is, I have spacing above it which has a sticky nav bar. I;ve tried adding padding to the top of the element it scrolls to, but when the user scrolls back up, there is space where the element has been offset.

Is there a way I can specify the offset on the page rather than the element in the jQuery for various breakpoints?

Hope that make sense

Thanks

Do you have an example you can show us? I think I get what you are saying, but seeing it in action would be better in providing you some options. Thanks. :slight_smile:

Danger, Will Robinson.

Unless you have very specifically crafted your page, you do not know the offset of the element prior to execution of the command. That’s why the jQuery function dynamically calls for the element’s offset.

You can modify where it puts the client by adding to the number retrieved by the jQuery function, but it would strongly advise against hardwiring flat numbers into it.

The following jQuery plugin might be useful.
jQuery.scrollTo

You can specify an offset for example, which you can obtain from the size of your sticky nav bar.

For example:

$("window").scrollTo("#scrollhash", "slow", {
    offset: -$("#stickynav").height()
});

Couldn’t the same be achieved by just subtracting the sticky nav height from the given scroll top though?

$('html, body').animate({
  scrollTop: $('#scrollhash').offset().top - $('#stickynav').height()
}, 'slow')

Hi,

Thanks for the replies. I have figured out that I can achieve what I need with this jQuery:

jQuery(window).scrollTop(650);

However, I would like to apply different values to different break points. Is this possible with jQuery?

I currently have the following in CSS:


/* Large desktops and laptops */

@media (min-width: 1200px) {


}



/* Landscape tablets and medium desktops */

@media (min-width: 992px) and (max-width: 1199px) {


}



/* Portrait tablets and small desktops */

@media (min-width: 768px) and (max-width: 991px) {


}



/* Landscape phones and portrait tablets */

@media (max-width: 767px) {

}


/* Portrait phones and smaller */

@media (max-width: 480px) {

}

but would like to apply different jQuery in different breakpoints.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.