I am dynamically generating buttons on my site. To detect the click state of these elements, i believe you need to use jQuery’s on(). I have tried the following but it does not seem to work. Am I doing something wrong?
$('.press').on('click', function() {
alert('clicked'); //Does not trigger on dynamic elements
});
When you view my JSFiddle, notice that clicking on the Dynamically Generated Buttons do not produce a result.
When you want to delegate event handling, the selector goes on the element that will contain the dynamic elements (all the way up to
document), and the second argument of.onis the selector: see documentationI suggest trying to have as specific a selector as possible when using delegation so that a minimal amount of traversal is required. It usually doesn’t make a huge difference, though.