jQuery: how to scroll to certain anchor/div on page load?
There's no need to use jQuery because this is native JavaScript functionality
element.scrollIntoView()
i achieve it like this..
if(location.pathname == '/registration')
{
$('html, body').animate({ scrollTop: $('#registration').offset().top - 40}, 1000);
}
Use the following simple example
function scrollToElement(ele) {
$(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left);
}
where ele
is your element (jQuery) .. for example : scrollToElement($('#myid'));
I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.
Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.
$(document).ready(function(){
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var hash = location.hash.replace('#','');
if(hash != ''){
// Clear the hash in the URL
// location.hash = ''; // delete front "//" if you want to change the address bar
$('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);
}
});
});
See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.