I have a div container, which holds several "rows" of data, with each item in the list in it's own "listRow" div. I'm using jQuery to make the "listRow" divs selectable, by toggling the css styling when clicked. Also within each row is an image div that floats on the right side of it's parent "listRow" div and contains an onclick event. When I click on the image div, the onclick event fires, but the parent "listRow" div is also clicked and "selected".
How can I prevent from clicking through my image div?
pseudo html code:
<div class="listContainer">
<div class="listRow" id="listRow1">
<div class="listItemName">List item #1</div>
<div class="listItemIcon"><img src="images/icon.png"></div>
</div>
<div class="listRow" id="listRow2">
<div class="listItemName">List item #2</div>
<div class="listItemIcon"><img src="images/icon.png"></div>
</div>
</div>
jQuery code:
$("div.listRow").click(function(){
$(this).toggleClass("selected");
})
To disable clicking inside a div with CSS or JavaScript, we can set the pointer-events CSS property to none . Also, we can add a click event listener to the div and then call event. preventDefault inside.
You can't prevent click with css, you must use javascript. The dislpay:none only hide a element, in this case, a div.
To disable the click event on an element, we can use the pointer-events property. Simply set the pointer-events property to none to disable the click event on any element that you want. In the following example, we have disabled the click event for a button by simply setting its pointer-events property to none .
You can solve this problem using the “none” value of the CSS pointer-events property. In the case of using this value, the element will not react to the pointer-events. With the help of the CSS background property put your transparent background.
You'd use event.stopPropagation()
:
event.stopPropagation()
- Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
On the div.listItemIcon
's click()
event to prevent the event bubbling:
$('div.listItemIcon').click(function(e){
e.stopPropagation();
});
$("div.listRow").click(function(){
$(this).toggleClass("selected");
});
jsFiddle example here.
In the click function of the image if you grab the event and use the stopPropagation()
function then it should keep the event from firing the the element's parents. eg.
$('div.listItemIcon').click(function(e){
//your code here
e.stopPropagation();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With