Last active
December 16, 2015 16:19
-
-
Save jonsuh/5462198 to your computer and use it in GitHub Desktop.
Better Scroll-To Anchor 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
$(document).ready(function(){ | |
$(".anchorLink").click(function(e) { | |
e.preventDefault(); | |
anchorScroll( $(this), $($(this).attr("href")), 100 ); | |
}); | |
}); | |
function anchorScroll(this_obj, that_obj, base_speed) { | |
var this_offset = this_obj.offset(); | |
var that_offset = that_obj.offset(); | |
var offset_diff = Math.abs(that_offset.top - this_offset.top); | |
var speed = (offset_diff * base_speed) / 1000; | |
$("html,body").animate({ | |
scrollTop: that_offset.top | |
}, speed); | |
} |
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
$("html,body").animate({ | |
scrollTop: that_offset.top | |
}, { | |
duration: speed, | |
easing: "easeInOutSine" | |
}); |
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
$(".anchorLink").click(function(e){ | |
e.preventDefault(); | |
var this_offset = $(this).offset(); | |
var that_id = $(this).attr("href"); | |
var that_offset = $(that_id).offset(); | |
var offset_diff = Math.abs(that_offset.top - this_offset.top); | |
var base_speed = 100; // Time in ms per 1,000 pixels | |
var speed = (offset_diff * base_speed) / 1000; | |
$("html,body").animate({ | |
scrollTop: that_offset.top | |
}, speed); | |
}); |
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
<a id="#top"></a> | |
... | |
<a href="#top" class="anchorLink">Back to Top</a> |
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
$(document).ready(function(){ | |
$(".anchorLink").click(function(e){ | |
e.preventDefault(); | |
var id = $(this).attr("href"); | |
var offset = $(id).offset(); | |
$("html, body").animate({ | |
scrollTop: offset.top | |
}, 100); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment