Skip to content

Instantly share code, notes, and snippets.

@matpratta
Last active December 3, 2015 18:05
Show Gist options
  • Select an option

  • Save matpratta/2cbbb1c5377f78a9012e to your computer and use it in GitHub Desktop.

Select an option

Save matpratta/2cbbb1c5377f78a9012e to your computer and use it in GitHub Desktop.
jQuery plugin to smoothly scroll the page when a link referencing an element ID is clicked.
/* smooth.jquery.js (ver 1.0.3)
* by Matheus Pratta (http://matheus.io)
* Requires: jQuery
* Optional: jQuery UI (for animations other than 'linear' and 'swing') - required by default
*/
// Thanks Sebastien Lorber for this snippet
function canonicalize (url) {
var div = document.createElement('div');
div.innerHTML = '<a></a>';
div.firstChild.href = url; // Ensures that the href is properly escaped
div.innerHTML = div.innerHTML; // Run the current innerHTML back through the parser
return div.firstChild.href;
}
var smooth_scroll_default_easing = (jQuery.effects) ? 'easeInOutExpo' : 'swing'; // Default easing, dafaults to jQueryUI first, but can also run only on jQuery.
function smooth_scroll_position(element) {
var pos = $('html, body').scrollTop();
if(pos == 0) pos = $('body').scrollTop(); // Additional check, in case of Safari or Chrome
var els = [];
if(element) {
$('*').each(function(i, o) {
var visible = true;
if($(o).css('display') == 'none') visible = false;
if(Math.floor($(o).offset().top) == Math.floor(pos) && visible) els = els.concat(o);
});
}
if(els.length > 0) return $(els);
return pos;
}
function smooth_scroll_to(element, duration, easing) {
duration = duration || 1500;
easing = easing || smooth_scroll_default_easing;
$('html, body').stop().animate({
scrollTop: $(element).offset().top
}, duration, easing);
}
$(document).ready(function() {
$("a[href*=#]").click(function(e) {
var targ = canonicalize($(this).attr('href'));
var targ_id = targ.substring(targ.indexOf('#'));
var pos = targ.indexOf('#');
if(~pos) {
var url = targ.substring(0, pos);
var curl = document.location.href;
var cpos = curl.indexOf('#');
if(~cpos) curl = curl.substring(0, cpos);
if(curl == url) {
e.preventDefault();
var targ_element = $(targ_id);
smooth_scroll_to(targ_element);
}
}
});
});
@matpratta

Copy link
Copy Markdown
Author

Update (2015-0819): ver 1.0.2

  • By default it can now run without jQueryUI. It will fallback to jQuery's "swing" easing then.

@matpratta

Copy link
Copy Markdown
Author

Update (2015-12-03): ver 1.0.3

  • Added support to absolute URLs (it will know when you click a URL in same page)
  • Added 'canonize' function to resolve URLs (thanks Sebastien Lorber)

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