Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle clicks on an element but not clicks on links within that element

How do I handle clicks on an element but not clicks on links within that element? Say I have the following

<div class="section">
    Some text blah blah
    <a href="#">Link</a>
</div>
<script>
    $(".section").click(function() {
        // code to expand/collapse section
    });
</script>

And I want users to be able to click on .section in order to expand/collapse it but I don't want that to happen if they clicked on a link within that section.

like image 536
A-OK Avatar asked Nov 29 '25 23:11

A-OK


1 Answers

You can check the event target, and only do something if it is the div. Here is one example:

$(".section").click(function(e) {
    if(e.target.tagName !== "DIV") {
      //Not the div! 
    }
});

You can test various properties of the target, so if for example you had other child div elements, but didn't want to register clicks on those, you could use the className property:

e.target.className !== "section"

Here is a working example (using the tagName property).

like image 69
James Allardice Avatar answered Dec 02 '25 11:12

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!