Skip to content

Instantly share code, notes, and snippets.

@iamravenous
Last active April 23, 2024 09:05
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iamravenous/f06b341dbb8b0839a7b0 to your computer and use it in GitHub Desktop.
Save iamravenous/f06b341dbb8b0839a7b0 to your computer and use it in GitHub Desktop.
Smooth scrolling on page load if URL have a hash
/*
* Smooth Scroll on Pageload
* Smooth scrolling on page load if URL have a hash
* Author: Franco Moya - @iamravenous
*/
if (window.location.hash) {
var hash = window.location.hash;
if ($(hash).length) {
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, 'swing');
}
}
@Viktorres19
Copy link

Great thanks, Franco, for your work!

@brunocmoraes
Copy link

brunocmoraes commented Aug 6, 2020

Thank you Franco !

to prevent some console error when the div does exists: if ($(hash).length)

if (window.location.hash) {
    var hash = window.location.hash;

    if ($(hash).length) {
        $('html, body').animate({
            scrollTop: $(hash).offset().top
        }, 900, 'swing');
    }
}

@iamravenous
Copy link
Author

Thank you Franco !

to prevent some console error when the div does exists: if ($(hash).length)

Thanks, I didn't know this 2015 gist could still be useful, I updated the code with your suggestion!

@mp111x000
Copy link

Hi Franco - could you help me with this piece of your code: {scrollTop: $(hash).offset().top} - I understand this is an element of "styles" (per documentation) and it takes the hash element to the very top of the page, correct? I've been wondering what to do if I want it to position the hash a bit lower, not at the very top of the page... any suggestions?...

@iamravenous
Copy link
Author

Hey @mp111x000! offset.top obtains the coordinates of the element tagged by the hash.
You can use math operators to add or subtract pixels at your convenience.

scrollTop: $(hash).offset().top - 80

In this case 80 would be the difference in pixels you want to include.
You can also use another variable to calculate the size of an element, and use it instead of a fixed number.

@mp111x000
Copy link

Wow - this is exactly what I meant, sorry for the confused question. Works like a breeze, many thanks Franco! And all the best in the New Year.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment