Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing page from scrolling on focus switching

Tags:

I am new to mobile web/dev. My app is using jquery-mobile, phonegap and Compass (scss).

I have a problem on my login page :

logo and fields are contained in standard 'div' containers (data-role="content" data-type="vertical"). Background is colored.

when switching focus from login field to password field, the page slides up, which is what I don-t want to occur. I would like my logo and fields to stay in place, just like the Skype iOS App login page.

here is what happens :

bug description

I have tried several tricks, trying to block scroll events, or forcing page to scroll to 0,0, without success.

I am thinking about a new strategy now, maybe using top relative positioning for logo and fields, and catching focus events to scroll the page myself, on keyboard slide up (by animating top relative positioning coordinates).

Though this seems doable, I am wondering if this is the kind of work around used by the Skype iOS App team...

Any advice on technics used in this particular case is welcome!

cheers,

Fred

like image 629
soleshoe Avatar asked Oct 06 '12 08:10

soleshoe


People also ask

How do I stop pages from auto scrolling?

Disable in the browser: go to chrome://flags/#enable-scroll-anchoring and set "Scroll anchoring" to "Disabled".

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.

Does focus scroll to Element?

An element can be focused by either using the autofocus="true" attribute or calling the element. focus() method. In both cases, the browser will automatically scroll the element into the viewport.


2 Answers

I think you want to call focus on the element directly and use the 'preventScroll' option.

el.focus({preventScroll: true});

$('#el').focus((e) => {
  e.preventDefault();
  e.target.focus({preventScroll: true});
})

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

like image 136
Gabriel Mahan Avatar answered Sep 20 '22 17:09

Gabriel Mahan


I haven't tested this yet, but does e.preventDefault() stop the issue? Generally you use e.preventDefault() to stop default scrolling / dragging behaviour.

$(document).bind('focus', function(e){
  e.preventDefault();
});

or better

$(element).bind('focus', function(e){
  e.preventDefault();
});

or

$(document).bind('touchstart', function(e){
  e.preventDefault();
});

Would an input field work better?

$(":input").live({
  focus: function(e) {
    e.preventDefault();
  }
});
like image 38
Jonathan Tonge Avatar answered Sep 21 '22 17:09

Jonathan Tonge