Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery focus without scroll

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

and this link is not visible in the screen (ex. is bellow the visible area) the browser scrolls down to show the element. How can I set the focus without scrollbar movement? I need to stay the scrollbar in the original place.

I have tried this, but it produces some screen flickering, and it is a hack, not an elegant solution:

var st=$(document).scrollTop(); $('#link').focus(); $(document).scrollTop(st); 

Can somebody help me, please?

like image 233
buzoganylaszlo Avatar asked Feb 04 '11 12:02

buzoganylaszlo


People also ask

Does focus scroll the page?

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

Can we set focus on Div?

Yes - this is possible. In order to do it, you need to assign a tabindex...

How do you set focus on a specific element in HTML?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.


2 Answers

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.

like image 180
Felipe Martim Avatar answered Sep 28 '22 08:09

Felipe Martim


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

like image 28
Dan Eastwell Avatar answered Sep 28 '22 08:09

Dan Eastwell