Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to jump to a specific div which placed bottom of page using JavaScript?

I have a div which located at the bottom of the page:

<div id="myDiv"></div>

I want to go to this div after performing of my JS-function. In other words, I want to have my url become myurl#myDiv and to go to my div. But without reloading the page. How this can be done using JavaScript? Unfortunately I have not found a working solution for this issue. I am not using any JS-libraries and frameworks.

like image 490
Michael Avatar asked Sep 05 '12 14:09

Michael


People also ask

How to scroll down to particular div using JavaScript?

The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.

How do you scroll down to an element in Javascript?

Scrolling to an element can be achieved in Javascript using the scrollIntoView() method. Smooth animation and customizing the alignment can be set through the scrollIntoViewOptions parameter.

How do you jump a div in HTML?

By prepending your href with # , you can target an HTML element with a specific id attribute. For example, <a href="#footer"> will navigate to the <div id="footer"> within the same HTML document. This type of href is often used to navigate back to the top of the page.


2 Answers

To scroll to a particular element, use, scrollIntoView, supported by IE6+ and real browsers:

document.getElementById('myDiv').scrollIntoView();

Check window.location.hash on DOMReady, to see if there is a hash in the URL matching any element in your document.

If there are #myDiv links within the document, you would need to add onclick listeners to them, perform the scroll manually, as per the code above, and return false to avoid following the link to #myDiv.

Demo

like image 50
David Hedlund Avatar answered Oct 22 '22 12:10

David Hedlund


Try setting the window's location to that of the ID. The browser will then scroll to that element.

window.location.hash = '#myDiv';
like image 11
Robert K Avatar answered Oct 22 '22 13:10

Robert K