Royi Namir
Royi Namir

Reputation: 148624

Get the top element in jQuery

I've built advanced validation plugin which shows the errors in a specific way.

However , when a user input is not valid , I scroll the page to the first element that has failed in validation.

this is how it looks :

enter image description here

So where is the problem ?

I've bolded the TD's in black.

So you can see that Currency textbox is on the first TD where Owner Name textbox is on the second TD

so Currency textbox has validated first , and so , the page scroll to the Currency location and not to the OwnerName text box location . ( as I wish)

Question :

How can I find the topmost element ( lets assume that all failed elements has .failed class - just for simplicity).

Upvotes: 3

Views: 187

Answers (4)

epascarello
epascarello

Reputation: 207527

There is nothing in jQuery built in to give what you want. You would have to loop through all of the elements and use offset() to see which one has the smallest top and left.

var failed = $(".failed");
var firstElem = failed.eq(0);
var firstPos = firstElem.offset();
failed.splice(0,1);
failed.each( function() {
    var elem = $(this);
    var pos = elem.offset();
    if (pos.top < firstPos.top || (pos.top===firstPos.top && pos.left<firstPos.left) {
        firstElem = elem;
        firstPos = pos;
    }    
});

Upvotes: 2

Alnitak
Alnitak

Reputation: 339917

Just iterate through each of the elements:

var $failed = $('.failed');
var top = null;    // current "smallest" value
var found = null;  // current "topmost" element

$failed.each(function() {
    var $this = $(this);
    var cur = $this.offset().top;
    if (top === null || cur < top) {
        found = this;
        top = cur;
    }
});     

Alternative, if you don't actually care which element it is, but just want the scroll position:

var tops = $failed.map(function() {
    return $(this).offset().top;
}).get();

var top = Math.min.apply(null, tops);

NB: code corrected to use .offset instead of .scrollTop

Upvotes: 7

David Hedlund
David Hedlund

Reputation: 129802

You could use sort to sort by position:

var topElement = $('.invalid-elements')
    .sort(function(a, b) { return $(a).offset().top - $(b).offset().top })[0];

Demo

Upvotes: 2

97ldave
97ldave

Reputation: 5249

Try this:

var el;

$.each($(".failed"), function () {
    if (!el || el.offset().top > $(this).offset().top) {
        el = $(this);
    }
});

Upvotes: 2

Related Questions