Betlista
Betlista

Reputation: 10549

How to detect overlapping HTML elements

Is it possible to find easily elements in HTML page that are hidden by given element (div)?

I prefer jQuery if possible. Do you know such plugin or something?

I searched in jQuery API (http://api.jquery.com/), but didn't find something useful.

Upvotes: 4

Views: 5070

Answers (3)

GibboK
GibboK

Reputation: 73918

You can use the following script:

http://jsfiddle.net/eyxt2tt1/2/

Basically what it does is:

  • calculating the dimensions of each DOM element, and comparing with user's mouse coordinate
  • if the match return a list of DOM elements

$(document).click(function (e) {
    var hitElements = getHitElements(e);
    var output = $('#output');
    output.html('');
    for (var i = 0; i < hitElements.length; ++i) {
        output.html(output.html() + '<br />' + hitElements[i][0].tagName + ' ' + hitElements[i][0].id);

    };

});

var getHitElements = function (e) {
    var x = e.pageX;
    var y = e.pageY;
    var hitElements = [];
    $(':visible').each(function () {
        console.log($(this).attr("id"), $(this).outerWidth());
        var offset = $(this).offset();
        console.log('+++++++++++++++++++++');
        console.log('pageX: ' + x);
        console.log('pageY: ' + y);
        console.log($(this).attr("id"), $(this).offset());
        console.log('+++++++++++++++++++++');
        if (offset.left < x && (offset.left + $(this).outerWidth() > x) && (offset.top < y && (offset.top + $(this).outerHeight() > y))) {
            console.log('included: ', $(this).attr("id"));
            console.log('from 0p far x: ', $(this).attr("id"), offset.left + $(this).outerWidth());
            console.log('from 0p far y: ', $(this).attr("id"), offset.top + $(this).outerHeight());
            hitElements.push($(this));
        }
    });

    return hitElements;

}

Upvotes: 0

maaachine
maaachine

Reputation: 821

It sounds like you're looking for something for debugging purposes, but please let me know if I've missed the question!

Firefox has a pretty neat 3D view (info here) that lets you see (more or less) exactly how the objects are being stacked. If you've never looked at it before, it's at least cool enough to check out.

Upvotes: 2

VisioN
VisioN

Reputation: 145398

One possible solution is jQuery Collision extension: http://sourceforge.net/projects/jquerycollision/.

JQuery extension to return the collisions between two selectors. Handles padding, margin, borders, and can determine either overlap or portion outside. Returns JQuery "overlap" objects. Requires: jquery1.8.3+, examples also require: jqueryui1.9.2+

Upvotes: 6

Related Questions