0

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);
  • The title of the duplicate question is almost identical to yours. How did you miss it in your searches? – Barmar Apr 14 '17 at 21:49
  • How did I miss it? Well, I didn't. I looked at it, saw it didn't answer my question, then asked a different one... I'm not asking how to do it at all, I already know how. I'm asking for a different way from then the one that I know and the one you are calling a 'duplicate'. The way the 'duplicate' is doing it is appending one event at a time to one element. I want to create the events on elements, concatenate them, and then append. Not one a time. – Jordan Little Apr 14 '17 at 22:04
  • The correct way to do it is with event delegation, which is shown in the duplicate question. – Barmar Apr 14 '17 at 22:05
  • It's the very first line of the first answer. – Barmar Apr 14 '17 at 22:06
  • `$(document).on('click', '.click', function)` – Barmar Apr 14 '17 at 22:06
  • The very first line of the first answer is my fourth line of code... The exact way I do not want to do it. – Jordan Little Apr 14 '17 at 22:07
  • No it isn't. Your code uses the 2-argument form of `on`, you need to use the 3-argument form. – Barmar Apr 14 '17 at 22:16
  • With 2 arguments it's normal event binding, with 3 arguments it's event delegation. Event delegation works on dynamically-created elements. – Barmar Apr 14 '17 at 22:17

0 Answers0