0

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>

5 Answers 5

3

You could try:

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

Just a thought

Sign up to request clarification or add additional context in comments.

5 Comments

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)
That's what I would do if I was stuck with this kind of HTML. Maybe eval($('#mydiv script').text()); is clearer.
@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.
This works, thanks. Why do you think it is asking for troubles? The script is not user created.
@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.
3

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();

1 Comment

This would be the best solution if I could refactor the code, thanks.
0

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.

Comments

0

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.

Comments

0

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

Something like :

$('script').each(
   function() {
      eval($(this).text());
   }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.