I want to dynamically add events onto elements using jQuery before adding them to the DOM.
The way I have been doing it is the following:
var biggerHTML = '<div> <p class="click">Click</p> </div>';
$(body).append(biggerHTML);
$('.click').off('click, function);
$('.click').on('click, function);
// The reason I have the off is because I will be dynamically adding in these a few times.
// It may make more sense why I felt like I had to do it when you read the next example.
I couldn't figure a way around unbinding my function from all the 'p' elements with class 'click' before adding the same function to the same selectors. What would happen would be my function would be bounded twice to the first element if I have two of the elements, it would bind three times if I had three elements. So, everytime I clicked, it would run two or three times. I know I could count the amount of class 'click' in the DOM then when I add my element again, give it an id of count+1 and then bind to the id, but I wanted to find something closer to the following.
var button = '<p> Click </p>';
$(button).on('click', function);
var biggerHTML = '<div>' + button + '</div>';
$(body).append(biggerHTML);