0

i want to execute jquery scripts in jquery html method. Like

$(body).html("<div id='mydiv'></div><script>$('#mydiv').fadeIn();</script>");

or

$(body).append("<div id='mydiv'></div><script>$('#mydiv').fadeIn();</script>");

div is inserted but javascript code not run.

How code can be runned?

Pavel
  • 1

1 Answers1

2

You should try something like this:

$(body).append("<div id='mydiv'></div>");
$('#mydiv').fadeIn();

After first line executing there are mydiv appears in DOM, so you can access it directly from your current script.


Edit (after comments)

If you want add script to you DOM using jQuery you should do it in some tricky way:

$("<script>$('#mydiv').fadeIn();</" + "script>").appendTo(document.body);

or

$("\x3Cscript>$('#mydiv').fadeIn();\x3C/script>").appendTo(document.body);

Without escaping or breaking </script> tag it terminates the entire script.

If you have more issues with your code please refer to next answer https://stackoverflow.com/a/3603496/1430055 where you can find explanations about debugging such a dynamic script, etc.

Community
  • 1
  • 1
Maxim Kolesnikov
  • 5,075
  • 6
  • 38
  • 68
  • Yes, this is workong but iam want to put $(body).append(var); where var is variable with javascript code; – Pavel Sep 20 '13 at 11:08
  • OK, in this case your question looks like duplicate. There is a detailed answer for the same question: http://stackoverflow.com/a/3603496/1430055 – Maxim Kolesnikov Sep 20 '13 at 11:43
  • Thankyou but this is only for scripts, iam want to put mixed contents. HTML text with javascript. Javascript is working but Jquery is not working. - $(body).append("
    "); is working, - $(body).append("
    "); - not working
    – Pavel Sep 20 '13 at 12:25
  • I found another bug in your code. You are using incorrect jQuery selector for body tag. It should be enclosed in quotes. Please look at this working example: http://jsfiddle.net/TBW9W/ – Maxim Kolesnikov Sep 20 '13 at 20:18