Scroll to a Section having id attribute using jQuery

Introduction

We will see how to scroll to a section having id attribute using jQuery API. Suppose you have several links at the top of the page and manually scroll down to a particular section you just need to click on a link and you will simply jump to the section without scrolling down. Such section may be paragraph, div etc. with an id attribute.

Such kind of situations are suitable when you want to have a table of contents with headings at the beginning of your blog and you want to point to the section on the page where actual content exists.

Prerequisites

jQuery, HTML

Create Sections

I will create two sections, one is with <p/> tag and another is with <div/> tag. I will put sample text into each of the sections. I will put an id attribute into each of the HTML tags.

I will create two anchor links which will take you to the particular section when you click on a link.

Create link at the top of the page:

<a href="#para_one">Paragraph One</a>
<a href="#para_two">Paragraph Two</a>

Create sections with paragraphs. One is with <p/> tag:

<p id="para_one">
	<h2>Paragraph One</h2>
	Sample text is being cut and pasted again and again.
        ...
</p>

Another is with <div/> tag:

<div id="para_two">
	<h2>Paragraph Two</h2>
	This is a sample Blog post.
        ...
</div>

Scroll to Sections

Here comes the jQuery part that will jump to the particular section when clicked on a particular link.

$("a[href^='#']").click(function(e) {
	e.preventDefault();
	
	var location = $($(this).attr("href")).offset().top;

	$("body, html").animate({
		scrollTop: location
	}, 100 );
});

In the above code snippets we have used click() function from jQuery to catch the click event on an anchor tag.

Then we get the position of the section from the href attribute’s value that points to the id attribute of the paragraph or div.

Next we use animate() function to go to the particular section. We use the speed value 100 to indicate how fast we want to jump to the section.

The scrollTop property in jQuery is used to set or return the vertical scrollbar position of any element. Setting the scrollTop to any value will make the page scroll to that location. The scroll by default takes place immediately and abruptly scrolls to the value.

Download Source Code

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *