Last active
April 21, 2018 13:30
-
-
Save janzikmund/4bce7c60fbfd1d49ae41920ae1211669 to your computer and use it in GitHub Desktop.
WordPress JS scrolling within pages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(function($) { | |
// get vertical offset of element by selector | |
var getElOffset = function(selector) { | |
var offset; | |
if(selector === '#top') { | |
return 0; | |
} else { | |
offset = $(selector).offset(); | |
if(typeof offset === 'undefined') return false; | |
offset_top = offset.top - $('header').outerHeight(); | |
if($('#wpadminbar').length) { | |
offset_top -= $('#wpadminbar').outerHeight(); | |
} | |
return offset_top; | |
} | |
}, | |
scrollToEl = function(selector) { | |
var offset = getElOffset(selector); | |
$('html, body').animate({ | |
scrollTop: offset, | |
}, 400); | |
}; | |
// bind scrolling links | |
$('a[data-scrollto]').on('click', function(e) { | |
var selector = $(this).data('scrollto'); | |
e.preventDefault(); | |
if($(selector).length > 0 || selector === '#top') { | |
// disable mobile menu if that we the trigger and scroll | |
$('body').removeClass('mobile-nav-active'); | |
scrollToEl(selector); | |
} | |
}); | |
// if URL contains scrolling hash, scroll there | |
if(window.location.hash !== '' && window.location.hash.substring(0, 8) === '#scroll-') { | |
var location = '#' + window.location.hash.substring(8); | |
setTimeout(scrollToEl, 500, location); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment