JavaScript

Javascript Jump To Div Examples

At times it might be desirable to jump to a specific div in a web page, just like a named anchor. If you don’t know what a named anchor is, in brief, it is a link within a page, rather than a link to a separate page. So, can we simulate the same behavior, for a div? Yes, we can! In this article, I am going to share a very easy example of  jumping to a div using JavaScript on page load. Read on to find out more.

How To Jump To Div Using JavaScript

Let’s assume that we have few divs with ID “my_div1”, “my_div1” and “my_div3” in a page. my_div1 is filled with lot of empty space. So this means that to actually view the contents of my_div2, you would normally have to scroll down, once the page loads. Now instead of this, we  would like to actually jump to my_div2 immediately on the page load. Note that these are all divs and not named anchors. The following example code achieves this effect.

Example:

<style type="text/css">
.new_div {
	background-color: #FFDF9D;
	border: 1px solid #F90;
}
</style>

<div id="my_div1" class="new_div">This is MY DIV 1
<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>

</div>

<div id="my_div2" class="new_div">This is MY DIV 2 --- You will directly start seeing this section instead of the My DIV 1 when the page loads. THis is because of the jump to div using the JavaScript code below.
<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>
</div>

<div id="my_div3" class="new_div">This is MY DIV 3</div>

<script language="javascript" type="text/javascript">
document.getElementById('my_div2').scrollIntoView();
</script>
Your Turn!

Do you know of any other ways to jump to any desired div using JavaScript on page load? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*