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();
}
4
  • 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. Commented Jun 26, 2015 at 18:06
  • And how would I do that? Commented Jun 26, 2015 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 (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. Commented Jun 26, 2015 at 18:13
  • @AdamBuchananSmith did you try my answer it should work for you... Commented Jun 26, 2015 at 18:20

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

6 Comments

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.
@AdamBuchananSmith I did a simple test on my machine and it worked...The scroll stayed where it was and the cursor was in the <input> field...Maybe you have something else different. I will post a fiddle for you.
Yeah, I obviously have another issue. I will post when I can figure out WTH is going on.
@AdamBuchananSmith if you want go ahead and post more code in your question if it's not too much just post your full page...
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.