1

I need to navigate to the element 'divElem1', on click of a button. Is it possible? If we enter this link in browser, http://myUrl#divElem1, browser will navigate to the page and to the DIV element 'divElem1'. The same behavior has to be obtained through javascript.

The hash change will not work in my application, as there are other events will be fired on hash change. So, the following will not work.

document.button.onclick = function () {
    location.hash = "#divElem1";
};

document.getElementById("divElem1").focus() is also not working since the element is a div

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
teknochamp
  • 13
  • 3

2 Answers2

4

You can use scrollIntoView for that:

document.getElementById("divElem1").scrollIntoView()

This doesn't give fine grain control over where exactly the target element will end up but it WILL be moved into the view-port. Even more, if the element is inside a scrollable container, both the container and the element inside it will be moved into a position so they are visible in the view-port.

marekful
  • 14,986
  • 6
  • 37
  • 59
1

If you want "plain" Javascript, use scrollIntoView(). But it really jumps to that position, see this question and answer.

Using jQuery, it can be done jumpy or with some easing, as explained here.

Easing is recommended to provide a better user experience and to let visitors see and understand what is happening.

Community
  • 1
  • 1
Jacco
  • 3,251
  • 1
  • 19
  • 29