3

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');
});
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • You need to make it a `live` type function. https://stackoverflow.com/questions/8021436/turning-live-into-on-in-jquery – Steve Apr 17 '18 at 12:33

3 Answers3

3

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>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

try

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

check example: https://jsfiddle.net/xpvt214o/142428/

Edin Puzic
  • 998
  • 2
  • 19
  • 39
  • This only works because you're not changing the classes on the hover event like the OP is. You need to use event delegation for this to work as the OP requires. – Rory McCrossan Apr 17 '18 at 12:44
  • @RoryMcCrossan It does not make sense add the class on hover using jQuery. You can do it using just CSS – Edin Puzic Apr 17 '18 at 12:57
0

Update from

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

to

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

Reason - It is possible that the element and or class on element was not present at the time the selector ran to bind the elements. Hence, use on for dynamic elements.

For reference - jQuery.on

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59