Search code examples
javascriptmouseoverelementstacked

have event listener effect multiple items in a stack


I am trying to figure out how to have an event listner change the class for multiple items that are stacked on top of each other.

I have a current fiddle here that I am working on, basically when someone clicks the button and hovers an object it changes the class of the object that is hovered. I would like to take this a step further so that when two object are positioned on top of eachother that both objects will be effected. Is there an easy way to do this?

Currently when you click and hover it only effects the top-most element. I would like to effect both the top and bottom element. Any help would be greatly appreciated!

http://jsfiddle.net/Ltdgx363/1/

obj=document.getElementsByTagName("object");
var mouseDown = 0;
document.onmousedown = function() { 
++mouseDown;
}
document.onmouseup = function() {
  --mouseDown;
}
for(i = 0; i < obj.length; i++) {
obj[i].addEventListener("mouseover", colorred ,false);
}
function colorred(){
if(mouseDown>0){
    this.className = "red";
    }
}

Solution

  • Assuming I understood your question correct, you can do that with jQuery parent() and children(). See my fiddle: http://jsfiddle.net/yu404vf2/2/

    Your function basically becomes like:

    function colorred(){
        if(mouseDown>0){
            this.className = "red";
        }
        $(this).parents().class = "red";
    }
    

    This works if objects are stacked like:

    <object id="object3">Test3
     <object id="object4">Test4</object>
    </object>
    

    But not if objects are stacked due to z-index/ position absolute.

    If you need the objects below the mouse pointer there is a nice function in javascrtipt called elementFromPoint which you can use like:

    var x = event.clientX, y = event.clientY,
    elementMouseIsOver = document.elementFromPoint(x, y);
    elementMouseIsOver.class="red";
    

    Updated jsfiddle: http://jsfiddle.net/yu404vf2/5/

    Hope that helps.