Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9457

Input focus using javascript

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();
}

Upvotes: 2

Views: 2172

Answers (1)

brso05
brso05

Reputation: 13232

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

Upvotes: 1

Related Questions