0

Another toggleClass() problem. There are dozens question about this jQuery function but I could not find this specific one.

I have 2 buttons. One toggles the class of the other on click. This works fine since the colour changes, however when I use a click() event on the 'new' class nothing happens.

html

<button type='button' id='button1'>button 1</button>
<button type='button' id='button2'>button 2</button>

css

.pushed {
    background-color: salmon;
}

js

$('#button1').click(function () {
  $('#button2').toggleClass('pushed');
});

$('.pushed').click(function () {
  alert('pushed!')
});

you can try it here: https://jsfiddle.net/tk9pt3o2/

skamsie
  • 2,614
  • 5
  • 36
  • 48

2 Answers2

2

Because you select the element with .pushed before even exists. Try to use this:

$(document).on('click', '.pushed',function () {
  alert('pushed!')
});

on will bind the click event to the current matched elements and future matched elements.

Ismail RBOUH
  • 10,292
  • 2
  • 24
  • 36
0

Consider that you can just register event for an existing Dom elements. the key point is $('.pushed') return jquery object with no element to register the event on it.

r0ck
  • 173
  • 12