Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: doesn't recognize mouse click [duplicate]

It really simple, but for some reason the second segment doesn't work at all. Clicking a card doesn't do ANYTHING.

$('.container__card').hover(function(){ 
    $(this).toggleClass('container__card container__card--hover')
});

$('.container__card--hover').click(function(){
   $(this).toggleClass('container__card--selected container__card--hover');
});

1 Answers

As you are adding classes dynamically so use jQuery event delegation

$(document).on('click' , '.container__card--hover', function(){
   $(this).toggleClass('container__card--selected container__card--hover');
});

Working snippet:-

$('.container__card').hover(function(){ 
   $(this).toggleClass('container__card container__card--hover')
});

$(document).on('click' , '.container__card--hover', function(){
   $(this).toggleClass('container__card--selected container__card--hover');
});
.container__card--hover{
  color:green;
  font-size:20px;
}
.container__card--selected{
  color:red;
  font-size:30px;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container__card">First hover and then click me please!</div>
like image 183
Anant Kumar Singh Avatar answered Aug 01 '26 12:08

Anant Kumar Singh



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!