Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .click - exclude specific elements inside div

Tags:

jquery

I want .click to do nothing IF the user clicks <p>text</p> inside the div, for everything else I want the div .click to work.

HTML:

<div>
    <span>yes</span>
    <p>text</p>
</div>

Jquery:

<script>
$(document).ready(function() {

    $("div").click(function() {

        alert("woohoo!");

    }); 

});
</script>
like image 410
supercoolville Avatar asked May 18 '12 02:05

supercoolville


2 Answers

   $("div").click(function(e) {
        if($(e.target).is('p')){
            e.preventDefault();
            return;
        }
        alert("woohoo!");
    }); 

check the target of the click. this way you dont need to bind another event.

like image 164
mkoryak Avatar answered Oct 13 '22 23:10

mkoryak


<script>
$( document ).ready(function() {
    $( "div :not(p)" ).click(function( event ) {
        alert( "woohoo!" );
    }); 
});
</script>

This implies you don't care about text nodes as children of the <div> container.

like image 29
Fagner Brack Avatar answered Oct 13 '22 21:10

Fagner Brack