I’m semi-new to Javascript/jQuery so apologies in advanced if I’m missing something basic. I have a function that is triggered whenever a user types in an element with a specific class.
$('.relevantClass').keyup(function(){
//code...
});
Now this function may end up, depending on the situation, creating a good deal of new HTML including new instances of relevantClass through the .append() method.
var newHTML = <div class='relevantclass'>Content...</div>;
$('#wrapper').append(newHtml);
However, the jQuery selector does not seem to detect and execute the function when a user types in the newly created relevantClasses. I’ve checked the newly created Html and it has the correct class tags and old instances of the relevant class due work.
I’m guessing this has something to do with .append(); messing with the DOM and I need someway to “refresh” the selector and let it do its jQuery thing researching the DOM to find the new classes. Any thoughts on how to do this? Is there some jQuery method I can’t find?
You have to use
on()to attach events that work on dynamic content:Keep in mind that to work with dynamic content, you have to attach the event to
relevantClass‘s closest parent that exists on page load.Some people use
body, but you should get used to using parent elements as close as you can get to the dynamic content. This is so that event delegation occurs on a smaller scale.More info on
on()here.Also, I hope that
newhtmlvariable is wrapped in quotes.