4

Prevent from clicking on div

 2 years ago
source link: https://www.codesd.com/item/prevent-from-clicking-on-div.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Prevent from clicking on div

advertisements

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");
})


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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK