Problems with SCROLLTOP

1

I'm having problems with scroll-top . The implemented function should take the input that was with focus it takes it to the top with scroll-top , but it works satisfactorily only for the first clicks at the top of the page, and when I go down giving click it behaves unsatisfactorily instead of leading to the top of the page it leads to the bottom of the page. I have noticed that sometimes the value of position is negative, but this is not always.

I tried to make sure that there was room for the field to roll up. So the problem is not in scrolling space.

Below is my code:

var tamanho = screen.height - 108 - 80;
var inputs = $('input').get();

$(inputs).on('focus', function () {
  $(".ajusteTeclado").css("height", tamanho + "px");
  $(".ajusteTeclado").show();
  var pos = $(this).offset(),
      position = pos.top - 60;

 // positiohttp://pt.stackoverflow.com/q/108569/4995n = ((position < 0)? position * -1 : position);
  console.log(position);
  $(this).closest('.scrollPosition').scrollTop(position);
});

What could it be?

I need every time the field has been in focus it should be located at the top of the page.

    
asked by anonymous 15.01.2016 / 18:50

1 answer

1

To solve this problem we have to understand the principle of objects:

The command $(this).offset() takes the position related to the field where focus is.

If we just take it and then run scrolltop() we see that it will rather lead to the top, but in the first click, where all div and field are zeroed in the directions of movement.

The problem happens there, it is necessary to get the current position of the field in relation to div , because it can happen that div is far above the field with focus , so the problem that sometimes reported negative values .

Then with this learning we conclude that we should take the current position of the field with focus + distance that the field is from the top, and in my case remove 60 px because I have a border. The final code looks like this:

var tamanho = screen.height - 108 - 80;
var inputs = $('input, textarea').get();

$(inputs).on('focus', function () {
  $(".ajusteTeclado").css("height", tamanho + "px");
  $(".ajusteTeclado").show();
  var pos = $(this).offset(),
      position = $(this).closest('.scrollPosition').scrollTop() + pos.top - 60;

 // position = ((position < 0)? position * -1 : position);
  console.log(position);
  console.log("Offset " + pos.top);
  $(this).closest('.scrollPosition').scrollTop(position);
});

Notice that in position I take the distance from the field on the screen and do as I explained above.

    
15.01.2016 / 20:04