How can I focus to a HTML element (ex. \"a\") and do not change the current scroll settings.
For ex. if I use:
$(\'#link\').focus();
<
I have the same problem, but in words: I think a more elegant solution would be to give the focus once the element is in the viewport.
Here's what I copy/pasted (Kudos to ADB from this thread Jquery check if element is visible in viewport)
$.fn.inView = function(){
if(!this.length) return false;
var rect = this.get(0).getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
window.$(window).on('scroll',function(){
if( $('#elementcontainingfocus').inView() ) {
$(function() {
$("#elementcontainingfocus input").focus();
$("input[type=text]:focus").css({
"box-shadow": "0 0 5px rgba(81, 203, 238, 1)",
"border": "1px solid rgba(81, 203, 238, 1)"
});
});
}
});
This worked for me
var focusWithoutScrolling = function(element) {
var fixed = { "position": "fixed" };
var posStatic = { "position": "static" };
$(":root").css(fixed);
$("body").css(fixed);
$("html").css(fixed);
$(element).focus();
$(":root").css(posStatic);
$("body").css(posStatic);
$("html").css(posStatic);
}
Try this:
$.fn.focusWithoutScrolling = function(){
var x = window.scrollX, y = window.scrollY;
this.focus();
window.scrollTo(x, y);
return this; //chainability
};
and then
$('#link').focusWithoutScrolling();
Edit:
It's been reported that this doesn't work in IE10. The probable solution would be to use:
var x = $(document).scrollLeft(), y = $(document).scrollTop();
but I haven't tested it.
$('#link').css('position', 'fixed').focus().css('position', 'static')
works in Firefox.
(Edit: You should not use this hack)
Try this jQuery solution:
$('#link').select();
Use {preventScroll: true}
option on the focus method. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
If using jQuery try $('#el')[0].focus({preventScroll: true})
or iterate over each in your collection