redirect to page section from anchor tag

How to Redirect URL/Page with Anchor Link

Sometimes you may need to redirect to a particular section of page using anchor text or link a div to particular section of your page. In this article, we will look at how to redirect URL/page with anchor link. You can do this using HTML, or using Javascript. We will look at both these methods.


How to Redirect URL/Page with Anchor Link

Here is how to redirect to particular section of your page, based on anchor link.


1. Using HTML

In this case, we add an id attribute to the div/section tag and use its value with #, as href attribute in anchor tag. Here is an example.

//anchor tag
<a href="#home_section">home</a>

<div id="home_section">Information About Page</div>

In the above code, we have used id=”home_section” for div tag. We have also used #home_section as the href for anchor tag. In other words, the href attribute of anchor tag should be created by prepending # to the id attribute of div/section. This tells the anchor tag to redirect to the div with id home_section, on clicking.

This is an in-built browser functionality supported by all major browsers. No need to use any libraries/plugins for it.


2. Using Javascript

You can also use jquery to redirect anchor tag to a specific section/div of your page. In this case, we add an event handler for click event of anchor tag. In that click handler, we use scrollTop function to return the vertical scrollbar position of selected element, that is the section/div that you want to redirect to.

Here is an example.

<a href="#" id="home">home</a>

$('#home').click(function(){
$(document).scrollTop(100) // any value you need
});

In the above code, we have added a click handler to our anchor tag. In that click handler, we use scrollTop function to return vertical scroll position of 100 from the top. In other words, we scroll down 100 pixels from the top of the page.

Conclusion

In this article, we have learnt two ways to redirect to particular section of page based on anchro link. Among them, it is advisable to use the HTML method since it is more precise than Javascript method and does not require any library/plugins to be used. In HTML method, since we redirect based on id of element, the browser will correctly reach the right section of your page. In case of javascript, we need to specify position of section/div in pixels, which can change in case of dynamic elements.

Also read:

How to Convert Docx to PDF using Python
How to Setup Passwordless SSH Login
How to Change NGINX User
How to Remove URL Parameters using .htaccess
How to Set Apache PATH Environment Variable

Leave a Reply

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