How can I scroll to an Element Using jQuery

How can I scroll to an Element Using jQuery

JavaScript can be used to manipulate HTML elements and create dynamic effects without having to refresh the page. JavaScript was originally developed by an employee for Netscape (that developed and made available the Netscape Communicator web browser and Internet suite) – with JavaScript originally named LiveScript, but was later renamed to JavaScript.

How do I dynamically scroll to the top or bottom of the window using JavaScript?

In the code example below,  I am scrolling to the top of a specific HTML element that makes use of a specific ID attribute value, but 40 pixels above this specific HTML element.

However, I am making use of the jQuery JavaScript library for ease of use and simplicity. You can download and use jQuery free. The code:

$(‘html, body’).animate({scrollTop: jQuery(‘#register’).position().top – 40}, ‘slow’);

You can change the #register value to whichever HTML element or ID that you want to scroll to. If you look at the code above, you’ll see the portion “.top – 40”, this is because the returns an integer value and by subtracting an extra 40 pixels, there will be some extra space when the “scrolling” is invoked – so it will stop at 40 pixels above the HTML element that uses the “register” ID attribute value.

How do I make use of jQuery?

In order to make use of the jQuery library, you need to include the library itself within the <head> section of your HTML document.

As well as that, you need to make sure that when you are making use of the library the HTML DOM is fully loaded before executing the JavaScript code making use of the jQuery library, so everything is ready prior to the execution of the JavaScript code. The full code below:

$(document).ready(function() {
$(‘html, body’).animate({scrollTop: jQuery(‘#register’).position().top – 40}, ‘slow’);