I have a search input text which I\'d like to apply a focus()
when loading the page, the problem is that the focus
function automatically does a sc
A bit modified version that supports more browsers (incl. IE9)
var cursorFocus = function(elem) {
var x, y;
// More sources for scroll x, y offset.
if (typeof(window.pageXOffset) !== 'undefined') {
x = window.pageXOffset;
y = window.pageYOffset;
} else if (typeof(window.scrollX) !== 'undefined') {
x = window.scrollX;
y = window.scrollY;
} else if (document.documentElement && typeof(document.documentElement.scrollLeft) !== 'undefined') {
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
} else {
x = document.body.scrollLeft;
y = document.body.scrollTop;
}
elem.focus();
if (typeof x !== 'undefined') {
// In some cases IE9 does not seem to catch instant scrollTo request.
setTimeout(function() { window.scrollTo(x, y); }, 100);
}
}
If you are using jQuery, you can also do this:
$.fn.focusWithoutScrolling = function(){
var x = window.scrollX, y = window.scrollY;
this.focus();
window.scrollTo(x, y);
};
and then
$('#search_terms').focusWithoutScrolling();
There is a new WHATWG standard which allows you you to pass an object to focus()
which specifies that you want to prevent the browser from scrolling the element into view:
const element = document.getElementById('search-terms')
element.focus({
preventScroll: true
});
It has been supported since Chrome 64 and Edge Insider Preview build 17046, and should be landing in Firefox 68 – a support matrix is available on web-platform-tests here.
As of today, the preferred way to set the focus on an element upon page load is using the autofocus
attribute. This does not involve any scrolling.
<input id="search_terms" type="text" autofocus />
The autofocus
attrubute is part of the HTML5 standard and is supported by all major browsers, with the only notable exception of Internet Explorer 9 or earlier.
I had a similar problem that was driving me crazy. Using jQuery, I've found a solution by discovering the coordinates of mouse and input and then scrolling to the difference between them. In your case it could be something like this:
document.addEventListener("mousemove", (e) => {
mouseCoords = { x: e.clientX, y: e.clientY };
});
$('#search_terms').bind("focus", function (e) {
var offset = e.offset();
window.scrollTo(
offset.left - mouseCoords.x,
offset.top - mouseCoords.y
);
});
Here's a complete solution:
var cursorFocus = function(elem) {
var x = window.scrollX, y = window.scrollY;
elem.focus();
window.scrollTo(x, y);
}
cursorFocus(document.getElementById('search-terms'));