Song Yongtao
Song Yongtao

Reputation: 835

Can't focus input after scroll?

In mobile browser, when focus input text, I want this input scroll to top

$(this.$el).find('input, textarea').on('focus', function(e) {
  setTimeout((function() {
    var pos = $(this).position();
    if (pos.top > window.innerHeight) {
      var scrollTopOffset = pos.top - window.innerHeight + this.offsetHeight + 10
      $scroller.scrollTop($scroller.scrollTop() + scrollTopOffset)
    }
  }).bind(this), 500); // After the keyboard up
  $(this).focus()
})

after the input scroll to the correct position, can't focus the input

touch the input then focus is ok, after that the keyboard up then the input scroll to top, then loose the focus

How to focus the input after scroll?

Upvotes: 0

Views: 511

Answers (2)

joashp
joashp

Reputation: 375

I have tried this, by emulating the browser for mobile and it works.

$('input, textarea').on('focus', function() {
    document.body.scrollTop = $(this).offset().top;
    $(this).focus();
});

Upvotes: 1

Hemangi Satasiya
Hemangi Satasiya

Reputation: 53

Hope This will help you.. Thanks

var cursorFocus = function(elem) {
      var x = window.scrollX, y = window.scrollY;
      elem.focus();
      window.scrollTo(x, y);
    }

    cursorFocus(document.getElementById('search-terms'));

Upvotes: 0

Related Questions