0

I have a few javascript functions that changes DOM elements, such as add classes, replace images, etc...

Now, sometimes a page will create a popup or will populate a navigation tree with some extra items without loading a new page. In that case the new element loaded will of course not be affected by my javascript.

For example. Say I give all images an extra class via javascript. Now the page generates a popup with some images in it, and then those images won't be affected by my javascript and the images in the popup won't get said class.

I was wondering if there is a way to make javascript behave like CSS - to be persistent or to work all the time, so that those new images will also be targeted by my scripts?

I hope that id clear :)

Thanks!

EDIT:

I will provide a bit more information here:

Say I have a simeple function like this:

$('.somediv').addClass( '.anotherclass' );

now this function is executed after the page loads.

Is there a way where I can automatically run this function again, when it is detected that a new div of class .somediv has been added to the DOM?

user1525612
  • 1,864
  • 1
  • 21
  • 33
  • Javascript isn't like CSS. It's only active when a function is called, and that usually happens when certain events happen - for example, most people will run some JS once the document is loaded. What you want to do is run javascript to set the css properties of the dynamic elements once the popup is triggered. – JTravakh Sep 11 '13 at 20:32
  • If I understand correctly you are asking about *Event Delegation* - best if you read about it here http://davidwalsh.name/event-delegate – Peter Pajchl Sep 11 '13 at 20:32
  • I guess I was wondering if there was an 'automatic' way of running my javascript function again each time the DOM changes? That way, in case of my image class, it would get added automatically every time a new image is added to the DOM? – user1525612 Sep 11 '13 at 20:38
  • Thanks Peter, I will have a read through this, this looks very helpful and something I know nothing of ;) – user1525612 Sep 11 '13 at 20:38
  • 1
    I guess you're looking for this: http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener/11546242#11546242 – Adassko Sep 11 '13 at 20:56
  • thanks, adassko, that looks ace! – user1525612 Sep 11 '13 at 21:43

1 Answers1

0

Whenever the new elements are dynamically added to the page you could call a javascript function that resets all the necessary classes and event bindings. Otherwise, if you know on the server-side what classes are necessary for these items you could send them over with the class already assigned to it.