1

I am using jQuery to validate a form, on submit I want to scroll to the first instance of the class .inputError which I have set up like this:

$('#form').submit(function(e) {
    e.preventDefault();
    $('input').each(function(){
        inputCheck.call(this);
    });
    errors = $('input.inputError').length;
    if (errors > 0) {
        $('body').scrollTop($('.inputError').first().offset().top-30);
    } else {
        submitForm();
    }
});

This works fine in Chrome/Safari, but in FireFox and IE8 it goes to the last instance of the class .inputError instead of the first. I have tried using $('.inputError:first) and .first() both produce the same result.

Any ideas?

user13286
  • 3,027
  • 9
  • 45
  • 100
  • My first guess would be malformed html. If you miss some closingtag somewhere that's (in my experience) the most likely reason for browsers to behave differently. – vrijdenker Sep 29 '14 at 19:51
  • 2
    Try using `$('body, html').scrollTop(...` – adeneo Sep 29 '14 at 19:53
  • @adeneo thank you for the suggestion, that did the trick! If you would like to add your comment as the answer, I will gladly accept. Thanks again! – user13286 Sep 29 '14 at 19:54
  • What version of jQuery are you using? Are you *sure* that its selecting the last instance? There's nothing in your demo code to illustrate this. IE8 might just be struggling with the offset() – Moob Sep 29 '14 at 19:54

1 Answers1

2

You should be using

$('body, html').scrollTop(... 

or alternatively

$(window).scrollTop(... 

if the scrollbar is global, as the scrollbar belongs to different elements in different browsers.

Here are a few plain JS solutions as well, if someone should need that in the future ->
Cross-browser method for detecting the scrollTop of the browser window

Community
  • 1
  • 1
adeneo
  • 312,895
  • 29
  • 395
  • 388