2

Is there a way to use javascript focus on an input without having the page scroll. I would like to have the curser start in the input field but I don't want it to scroll to that part of the page.

currently I am using

function setFocusToTextBox() {
    document.getElementById("FirstName1").focus();
}
Adam Buchanan Smith
  • 9,422
  • 5
  • 19
  • 39
  • 1
    Instead, why not give the input focus once it becomes visible in the viewport? This way you avoid the whole issue of the page jumping down to the input, and offers a better experience. – filoxo Jun 26 '15 at 18:06
  • And how would I do that? – Adam Buchanan Smith Jun 26 '15 at 18:08
  • That would be the basis of another question, but you would have to [calculate if the element is outside of the viewport](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport) (and probably need to bind this function to the `window.scroll` event), and when the element is not outside of the viewport, give it focus like you're already doing. – filoxo Jun 26 '15 at 18:13
  • @AdamBuchananSmith did you try my answer it should work for you... – brso05 Jun 26 '15 at 18:20

1 Answers1

1

You can get the scroll before then set the scroll after like this:

function setFocusToTextBox() {
    var doc = document.documentElement;
    var x = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
    var y = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    document.getElementById("FirstName1").focus();
    window.scrollTo(x, y);
}

Code take from these links: link1 link2

You can get the scroll location before the focus then set it back to what it was right after you focus...

Community
  • 1
  • 1
brso05
  • 13,142
  • 2
  • 21
  • 40
  • I am currently trying it, the page scrolls to the top but there is no cursor on in the text field so I am trying to work through what you gave me and see if I am doing something incorrectly. – Adam Buchanan Smith Jun 26 '15 at 18:23
  • @AdamBuchananSmith I did a simple test on my machine and it worked...The scroll stayed where it was and the cursor was in the `` field...Maybe you have something else different. I will post a fiddle for you. – brso05 Jun 26 '15 at 18:25
  • Yeah, I obviously have another issue. I will post when I can figure out WTH is going on. – Adam Buchanan Smith Jun 26 '15 at 18:42
  • @AdamBuchananSmith if you want go ahead and post more code in your question if it's not too much just post your full page... – brso05 Jun 26 '15 at 18:43
  • Ok, I am am going to mark your answer correct because it does answer my question. its not working for me on that page but I think its now due to having multiple different page scroll functions and one is overriding the other, today will be one of those days I guess. – Adam Buchanan Smith Jun 26 '15 at 18:57
  • @AdamBuchananSmith haha! it happens man...thanks and good luck! – brso05 Jun 26 '15 at 18:58