Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click function exception

Tags:

jquery

I am displaying a container <div class="expand"> that - when clicked on - expands the section below it:

HTML:

<div class="expand">
    <div class="container1">
         <div class="container2">
             <a class="view">View</a>
             <a class="download">Download</a>
         </div>
    </div>
</div>

<section class="hidden">
...
</section>

jQuery:

$('.expand').click(function () {

   var $this = $(this);
   $this.next().show();

});

As you can see, there also a "Download" button as a child element of the <div class="expand">. This Download button should be the only element in this very container that does not trigger the said section to be shown.

So I would like to do something like this:

$('.expand').not(".download").click(function () {
...
});

or

$('.expand').except(".download").click(function () {
...
});
like image 520
Frank Avatar asked Dec 14 '22 14:12

Frank


2 Answers

You can use event.stopPropagation() as well:

$('.download').click(function(event) {
    event.stopPropagation();
}

$('.expand').click(function () {
    ...
});

This will stop the event from moving up in the DOM to parents, and triggering their event handlers as well.

like image 97
Matthew Rapati Avatar answered Jan 15 '23 04:01

Matthew Rapati


use e.target to check clicked element is download or not

$('.expand').click(function (e) {

    if (!$(e.target).is(".download")) {
        var $this = $(this);
        $this.next().show();
    }

});
like image 27
Balachandran Avatar answered Jan 15 '23 06:01

Balachandran