Skip to content

Instantly share code, notes, and snippets.

@janzikmund
Last active April 21, 2018 13:30
Show Gist options
  • Save janzikmund/4bce7c60fbfd1d49ae41920ae1211669 to your computer and use it in GitHub Desktop.
Save janzikmund/4bce7c60fbfd1d49ae41920ae1211669 to your computer and use it in GitHub Desktop.
WordPress JS scrolling within pages
<?php
// replace basic links by scrolling ones if this is the page linked
$actual_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = str_replace('/', '\/', parse_url($actual_url, PHP_URL_PATH));
$main_menu = preg_replace('~<a href="' . $url_path . '#scroll-(.*?)">(.*?)<\/a>~i', '<a href="#" data-scrollto="#$1">$2</a>', $main_menu);
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