3

I want to add something to an element when its loaded / available.

<div class="main">
    <div class="dynamic">
     </div>
     <div class="dynamic">
     </div>
</div>

The first dynamic element is already available when the page is initially loaded. But the second one is loaded later by some javascript i cannot alter.

I tried it like this but that does not work:

$('.main').on('load/change', 'div.dynamic', function() {
    $(this).html("add something");
}):

Neither the first dynamic content is loaded nor the second one.

It is probably a simple task but i cannot find the answer.

I would appreciate some help.

MMM
  • 7,221
  • 2
  • 24
  • 42
Andy
  • 770
  • 2
  • 9
  • 21
  • 3
    There is no cross-browser event that will trigger when an element becomes available. Instead, do it when the element is added, such as in the success callback of an ajax request. – Kevin B Apr 09 '13 at 15:21
  • Why one could not alter a JS code? I think it's indespensable, otherwise you're gonna to rely on intervals or other exausting methods – Roko C. Buljan Apr 09 '13 at 15:22
  • maybe you could use this http://stackoverflow.com/questions/1091661/detect-element-content-changes-with-jquery – John Boker Apr 09 '13 at 15:23
  • 1
    How this div is *loaded*? An Ajax call? then use your AJAX callback – Mohsen Apr 09 '13 at 15:24
  • You're only option if you can't alter the code that is adding the div is to use a setInterval(or selfcalling function or global ajax handlers) that periodically checks for said div. That is very inefficient though, and will also require you to ensure you aren't affecting divs that already exist and have already been initialized. – Kevin B Apr 09 '13 at 15:24
  • Wow, that was fast, thank you guys. @John , i will look into that. The "loading" code is part of a theme which is hosted somewhere else. Thats the reason i cannot alter it. If i could i would have used the callback funktion. – Andy Apr 09 '13 at 15:29

2 Answers2

0

hey buddy you can use this code easily

<script>
$(document).ready(function() {
    $("div.dynamic").html("add something");
});

it works fine for me.

gagan
  • 1
  • 1
0

You could do something like this...

setInterval(function() {
    if($('.main .dynamic').length>1)){
        $('.main .dynamic').html("add something");
    }
}, 150);

Where 150 is the polling time in ms (it checks for the 2nd dynamic DIV every 150ms)

But as already stated this is not ideal, it would be better to find a way to access the AJAX event and attach it there if possible

DaveB
  • 2,953
  • 7
  • 38
  • 60