[RESOLVED] Initialise after jQuery alters DOM

Hello, all,

I’ve got a form that is for entering shipping information, and will allow the user to add cargo to an existing list (ie, the form loads with just one area for cargo, but if the user has three items he/she can click “add cargo” and another area for cargo information appears.) I’m also giving the user the option to remove a cargo item from the form.

Upon first click of the ‘remove’ link, it works. Subsequent clicks do nothing - not even an error message.

Granted, I’m assuming that the issue is because the DOM has changed, so jQuery needs to be re-initialised. Is there a way to reinit jQuery so it sees the updated DOM? Or am I completely off the mark?

V/r,

:slight_smile:

Hey,

Sounds like you’ll need to use event delegation. For example, this:

$(".myClass").on("click", function(){
  // Do stuff
});

will attach a click listener to every element with the class myClass present when the DOM renders.

If you are adding elements with the class myClass programatically, they will not have this listener attached.

To get around this, attach the listener to a parent element that is present when the DOM renders, then specify myClass as an additional argument.

E.g.

$("body").on("click", ".myClass", function(){
  // Do stuff
});

And that should work.

1 Like

Thanks, @Pullo, I’ll give that a shot!

V/r,

:slight_smile:

Brilliant, @James_Hibbard! Worked like a charm! Some things I can’t do that way, but the ones I can, I’m switching to that format! :smile:

:slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.