user13286
user13286

Reputation: 3075

jQuery :first and .first() behaving differently in Chrome/Safari and FireFox/IE8

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?

Upvotes: 1

Views: 199

Answers (1)

adeneo
adeneo

Reputation: 318302

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

Upvotes: 2

Related Questions