Robin Maben
Robin Maben

Reputation: 23084

How do get visual topmost element - jQuery

Is there a neat way to get the topmost element using jQuery?

I don't mean with respect to DOM hierarchy. i.e. .closest() is not what I need.

I mean, with respect to z-index and obviously it should be currently :visible

I was starting out to write a custom selector, but thought it would be better to see if there are better approaches.

Upvotes: 0

Views: 795

Answers (2)

Ram
Ram

Reputation: 144699

try this:

elem = [];
$("*").each(function(i){
    elem[$(this).index()] = $(this).css('z-index');
})

function compareNumbers(a,b) {
    return a - b;
}

topmostIndex = elem.sort(compareNumbers).reverse();
alert(topmostIndex[0])

Upvotes: 1

Rishabh
Rishabh

Reputation: 1205

try this:

$(':visible').each(function(){
    var z = parseInt($(this).css('z-index'), 10);
    vat maxz = -1;
    if (!best || maxz < z) {
        best = this;
        maxz = z;
    }

});

Upvotes: 0

Related Questions