Reputation: 18248
I inject a MustacheJS template (button element) into HTML. Then use JS to toggle CSS of buttons if clicked. This JS works on all buttons but not on those created by mustachejs:
function clickToggleCSS() {
$(this).toggleClass('status0').toggleClass('status1');
}
$('button').on("click", clickToggleCSS);
See this fiddle where the upper button is true HTML, and the bottom button is injected using MustacheJS.
How to make it work ? (fiddle appreciate!)
Solution (fiddle):
$('body').on('click', 'button', clickToggleCSS);
Upvotes: 0
Views: 132
Reputation: 413702
Try:
$('body').on('click', 'button', clickToggleCSS);
When you add a handler directly to elements (as in your code), then it only applies to the elements found at the time that that code ran. Elements added after that point are not affected. By using a delegated handler (in this case, on the <body>
element), then any "click" event on any future button will also be handled.
Upvotes: 3