- 24 March 2018
- JavaScript (2)
- jQuery (2)
Demo
Smooth scrolling is a lovely effect to take users to certain areas of content on your page. To test this functionality out try clicking this link. It should scroll you down to the comments.
Try clicking this link to see what would happen if JavaScript is disabled. On this occasion a simple anchor link is used.
Include jQuery
Remember to include jQuery first. You can either download jQuery and include it in your files, or include it using a CDN. Just add this line inside your head element to include jQuery via the Google CDN:
wp_enqueue_script('jquery-3-2-1-min', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
Create the Function
You’ll need to create and JavaScript file so you can add the code below to it. For reusable functions like this I like to create a file called general.js, which I include in the head element of my page. Add the code below to your JavaScript file:
// Scroll to anchor (passed parameter) function scrollTo(anchor){ $(‘html,body’).animate({ scrollTop: $(anchor).offset().top }, 1000); }
Calling the Function
Call the function above by passing an anchor tag as a parameter (e.g the div class/id you want to link to). In this example we’re linking to a div with the id #comments-anchor:
<a href="#comments-anchor" onclick="scrollToAnchor('#comments-anchor');return false;">Go to the comments</a>
- The href value is the fallback, just in case JavaScript is disabled
- Onclick runs the function and passes the parameter
- Return false stops the link from jumping to the top of the page before scrolling
How easy is that!
Comments
Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.