views:

36

answers:

5

I have some container on a page with inline javascript. Is there a way to trigger its execution once again after it was initially triggered automatically on a page load?

<div id="mydiv">
    <script type='text/javascript'>alert("trigger me again");</script>
</div>
A: 

You could assign it to a function and set a timer event ... There are two types of timers in javascript (setTimeout and setInterval). However, there are also some jQuery libs for event timers.

drachenstern
+3  A: 

You need to make a function:

<script type='text/javascript'>
function doSomething() {
    alert("trigger me again");
}
doSomething();  //Call the function immediately
</script>

You can then call the function again somewhere else:

doSomething();
SLaks
This would be the best solution if I could refactor the code, thanks.
serg
A: 

What I would do is make that inline javascript call be a function. Then you can call that function over and over after the page load.

Avitus
+3  A: 

You could try:

eval($('script', $('#mydiv')).text());

Just a thought

Bryan Ross
Why would you think this was an acceptable place for an eval? I think that's just asking for trouble, as it allows other could to be inserted in it's place (granted, we're talking about DOM walked changes, so doubtful to find too many bad uses directly, but I still think this code stinks ... #CodeSmell)
drachenstern
That's what I would do if I was stuck with this kind of HTML. Maybe `eval($('#mydiv script').text());` is clearer.
Tomalak
@drachenstern: At least I would not, because that's *exactly* what the browser does. That bit of code runs *anyway*, so where's the danger? Seeing `eval()` and crying "code smell" is a bit too eager.
Tomalak
This works, thanks. Why do you think it is asking for troubles? The script is not user created.
serg
@Tomalak I guess it's just a kneejerk reaction to the instruction to pepper the code with eval statements. I grok that the browser would have to do an eval on the initial insert, but I still find it to have #CodeSmell. Guess I would have to wait and see what I would actually do in that situation, since I really don't know all the variables, ya? Guess that's what makes us human, those differing opinions on how to do things.
drachenstern
A: 

I guess you can select your element and then eval() the code inside.

Something like :

$('script').each(
   function() {
      eval($(this).text());
   }
);
Boris Guéry