Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling mouse events on 'div'

I have an interesting problem in disabling mouse events using the 'pointer-events' css styling.

Please refer the fiddle. It has a parent and two children div, and I make 'pointer-events' as 'none' to one of the children. If I click on that div, its mouse listeners are not triggered (this is expected) but mouse events of its parent div is triggered.

$('#parent').click(function(){
   console.log("Parent clicked"); 
});

How to disable mouse events on the parent div, if I clicked on its children which are disabled for mouse events?

One option is to filter using an "if" condition on the parent click. But i don't need it, as I want to listen for mouse events on 'divs' present behind the parent.

Please provide some help :)

thanks, Rethna

like image 235
Rethna Avatar asked Apr 24 '14 06:04

Rethna


1 Answers

I couldnt make the pointer-events work as I intended, so I changed the javascript in order to achieve what you wanted. What i did was to event.stopPropagation on the child2, so you can click him and only fire his click event, not his parent's click event. By the way, i know little about jquery, so I wrote a mixed beetwen pure javascript and jquery, hope someone can help me translate that.

Here comes the fiddle

CSS:

child1{

background-color:#ff0000;
width:100px;
height:100px;
pointer-events: all;

}

child2{

background-color:#00ff00;
width:100px;
height:100px;
pointer-events: all;

}

parent{

 pointer-events: none;

}

Javascript:

$(document).ready(function(){
    document.getElementById('child1').addEventListener('click', function(){
        console.log("child1 clicked");
    }, false);
    
    document.getElementById('child2').addEventListener('click', function(e){
        e.stopImmediatePropagation();
        console.log("child2 clicked");
    }, false);
    
    document.getElementById('parent').addEventListener('click', function(){
        console.log("Parent clicked");
    }, false);
});
like image 142
Matheus Avatar answered Oct 13 '22 00:10

Matheus