![]() |
|
jQuery Universal Smooth Scrolling - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Design (https://sinister.ly/Forum-Design) +--- Forum: Web Design (https://sinister.ly/Forum-Web-Design) +--- Thread: jQuery Universal Smooth Scrolling (/Thread-jQuery-Universal-Smooth-Scrolling) |
jQuery Universal Smooth Scrolling - Inori - 01-07-2016 For any html container that can take an href parameter, you can redirect said href to another container with the specified id on the same page. Knowing this is convenient, but it looks bad, since the above method jumps directly to the element. That's where this comes in. The below snippet is activated for any click on the document on an <a></a> tag that's href value starts with an id tag, or #. What it will do is scroll the page to the desired location instead of jumping to it immediately, which looks a lot cleaner and more professional. Code: //listens for click in any <a href="#..."> tags
$(document).on('click','a[href^="#"]',function(e){
//get the element's target
var id=$(this).attr('href');
var $id=$(id);
//prevents the ugly, default jump
e.preventDefault();
var pos=$(id).offset().top; //gets current y distance from target
$('body, html').animate({scrollTop: pos},1000); //scrolls to top of target
});Note: Don't forget to link jQuery with the code below or this won't work Code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> |