Home » Jquery » jquery – Card is flipped when a child button (with different functionality) is pressed. How to stop the propagation to the parent?

jquery – Card is flipped when a child button (with different functionality) is pressed. How to stop the propagation to the parent?

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a card which is getting flipped when somebody presses on it (and that is totally fine) so the user can read more information from the back of the card. The card itself contains 2 buttons: 1st for redirecting the user to another page and the 2nd – triggering a modal popup.

The problem I am facing is when I press any of the buttons, both actions are performed. For example pressing the button triggering the modal pop up – the card is getting flipped and the modal appears (you can see the flipped card in the background).

How can I ‘isolate’ the clicks on the buttons not to trigger the card flip?

<div class="col-md-4 d-flex align-items-stretch">
   <div class="student-card">
      <div class="card" id="[email protected]" onclick= "this.classList.toggle('flipped');">
         <div class="card-body d-flex flex-column">
            <h3 class="card-title">Jesper</h3>
            <p class="card-text">Short Description</p>
            <button type="button" class="btn btn-primary redirect_1" click="window.location.href ='https://google.com';"> Read More </button>
            <button type="button" class="btn btn-primary opensend_1" id="opensend_1" data-toggle="modal" data-target="#sendview_1">Send msg</button>
         </div>
         <div class="side back d-flex flex-column">
            <h3>Jesper</h3>
            <p>About Jesper</p>
         </div>
      </div>
   </div>
</div>

I tried the stopPropagation(), but I could not make it work with my example.

How to&Answer:

You can do it with JQuery.

You can bind the click event to the card element, and when the user clicks the card, check if the target clicked is a button. If it isn’t a button, flip the card. Otherwise, do nothing, and the default button behavior will trigger.

This way the card will be flipped only when the user clicks the card, but not the element with the .btn class.

$("#[email protected]").on("click", function(e){
   if(!($(e.target).hasClass("btn"))){
       $(this).toggleClass("flipped");
   }
});