Last active
October 8, 2016 15:05
-
-
Save kadimi/3b284e5795250543bd4f504f817cba4a to your computer and use it in GitHub Desktop.
Simple solution to improve links click behaviour with jQuery by scrolling to hash removing useless page refresh when clicking on same page links.
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(document).ready(function($) { | |
/** | |
* Improve anchors click behaviour: | |
* - Scroll to hash | |
* - Prevent useless refresh when clicking on same page links | |
*/ | |
$('a').on('click', function(event) { | |
var $this = $(this); | |
var current_url_relative = window.location.href.replace(window.location.origin, '').split('#')[0]; | |
var href_url_relative = $(this).attr('href').replace(window.location.origin, '').split('#')[0]; | |
var is_same_page = current_url_relative === href_url_relative; | |
if (is_same_page) { | |
event.preventDefault(); | |
/** | |
* Position to scroll to. | |
* | |
* - No-hash: 0 | |
* - Hash: the position of the referenced element (uses HTML id attribute) | |
* | |
* @type Integer | |
*/ | |
var to = ($this.is('[href*=#]')) ? $(this.hash).offset().top : 0; | |
/** | |
* Scroll. | |
*/ | |
$('html,body').animate({scrollTop: to}); | |
/** | |
* Update address bar and history. | |
*/ | |
if (history.pushState) { | |
history.pushState(null, null, $this.attr('href')); | |
} | |
} | |
}); | |
/** | |
* Required for the back/forward buttons to work. | |
*/ | |
$(window).bind('popstate', function() { | |
window.location.href = window.location.href; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment