skamsie skamsie - 4 months ago 9
jQuery Question

class made with toggleClass() doesn't alert on click event

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/

Answer

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.

Comments