8

Possible Duplicate:
How to get a list of all elements that resides at the clicked point?

I know I can get the element with the highest z-index by using document.elementFromPoint(x,y).

The problem is I need to get every div that contains the touch event's location.

How can I propagate touches to elements underneath?

I have seen some hacky solutions that show/hide elements while re-generating the event, or pointer-events style with css, however I cannot use these and they may cause flickering...

The following diagram illustrates what I need to do:

If the purple, green, and blue boxes represent the div elements, and the red dot is the touch location, I need a function that would return "div3, div2, div1".

Community
  • 1
  • 1
Dustin Jackson
  • 377
  • 4
  • 13
  • I have a [plugin](http://jsfiddle.net/SpYk3/2FZVW/) I made a while back that does something similar with the cursor. I'm pretty sure the same principle can be applied to touch variable, however, here at work, i can't even make use of my fiddle, much less see my old un-mined code, I will try to remember this problem when i get home today and get ack up with you. For now, I've included a link to my plugin and perhaps you can find what you need in that "box" so to speak. g'luck! – SpYk3HH Oct 11 '12 at 20:21
  • It has a function in it which will return all elements under the cursor, tho its been a while since i've used it, so i cant tell you exactly which one off top of my head ([more plugin example use found on this SO answer](http://stackoverflow.com/questions/1843674/how-to-change-cursor-from-pointer-to-finger-using-jquery/10353324#10353324)) – SpYk3HH Oct 11 '12 at 20:22
  • 1
    You shouldn't be worried about momentarily hiding the elements, as the browser won't redraw until the function ends. – Shmiddty Oct 11 '12 at 20:30

2 Answers2

19

No flickering with this code:

$("body").click(function(e){
    var x = e.pageX, y = e.pageY;
    var res = [];

    var ele = document.elementFromPoint(x,y);
    while(ele && ele.tagName != "BODY" && ele.tagName != "HTML"){
        res.push(ele);
        ele.style.display = "none";
        ele = document.elementFromPoint(x,y);
    }

    for(var i = 0; i < res.length; i++){
        res[i].style.display = "";
    }
    console.log(res);
});​
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
2

What about doing:

 $(document).click(function(e) { 
    var pageX = e.pageX;
    var pageY = e.pageY;
    $('*').each(function(index) {
        var offset = $(this).offset();
        var left = offset.left;
        var right = offset.right;
        var width = $(this).width();
        var height = $(this).height();
        if(pageX > left && pageX < left + width) {
             if(pageY > top && pageY < top + height) {
                  //Handle the div
             }
        }
    });
});
Tom G
  • 3,650
  • 1
  • 20
  • 19