so my on click event to scroll down to the hashtag element class worked fine but i noticed if i requested from another page it did not scroll so i added window load which works lovely but now with both bits of code together the on load scrolls if a hashtag url is present but click no longer works... does anyone have a better solution for these to both work?
JS
// Scroll To # Links $('a[href^="#"]').on('click', function(e) { if (!$(this).hasClass("menu-button")) { e.preventDefault(); var target = this.hash; target = target.replace('#', ''); var $target = $('.' + target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 700, 'swing', function() { window.location.hash = '#' + target; }); } }); // Scroll on load if #hashtag set in URL $(window).load(function(e){ // Remove the # from the hash, as different browsers may or may not include it var loadTarget = location.hash.replace('#',''); if(loadTarget != ''){ e.preventDefault(); // Clear the hash in the URL // location.hash = ''; // delete front "//" if you want to change the address bar var $loadTarget = $('.' + loadTarget); $('html, body').stop().animate({ 'scrollTop': $loadTarget.offset().top }, 700, 'swing', function() { window.location.hash = '#' + loadTarget; }); } });
HTML:
<a href="#test">test link</a> <div class="test" style="margin-top: 1000px;"> testing content </div>