Youstay Igo
Youstay Igo

Reputation: 331

Dynamically Adding JavaScript Code To Page

This question is linked with Frustrating innerHTML Issue.

Since this question was a duplicate of another question, so I referred to that question for a solution. I adopted the 2nd answer in the list (with 37 votes). So that I used this coding for dynamically adding javascript to my page.

<html>
<head><title>Javascript Using innerHTML</title>
<script type="text/javascript">
    function setcode(code)  {
    document.write("<img src='empty.gif' onload='function msgbox(msg){alert(msg);};' />");
    }
</script>
</head>
<body onload="">
<div id="hello">
    &nbsp;
</div>
<button onclick='setcode(document.getElementById("hello"))'>SET</button>
<button onclick='msgbox("what up man?!");'>CHECK</button>
</body>
</html>

Now the issue is that when I press the SET button, all my current page is removed out of existence and only the code within document.write() remains. Am I doing something wrong or what? Note that I want to add javascript coding to my page without removing the current visual objects :S

Upvotes: 0

Views: 129

Answers (2)

Youstay Igo
Youstay Igo

Reputation: 331

OK, I found a brilliant working solution for my problem. It is the second answer posted at Can I add javascript dynamically to an existing script element

<html>
<head><title>Javascript Using innerHTML</title>
<script type="text/javascript">
    function setcode(code)  {
    var JS=document.createElement("script");
    JS.text="function msgbox(msg){alert(msg);}";
    document.body.appendChild(JS);
    }
</script>
</head>
<body onload="">
<div id="hello">
    &nbsp;
</div>
<button onclick='setcode(document.getElementById("hello"))'>SET</button>
<button onclick='msgbox("hello");'>CHECK</button>
</body>
</html>

works flawlessly without any glitch or issue. Thanks to kennebec for the answer.

Upvotes: 0

filype
filype

Reputation: 8380

the issue is that when I press the SET button, all my current page is removed out of existence and only the code within document.write() remains

That's the expected behaviour for the document.write function. It will overwrite all the content on the page.

You need to instead append content to the page you can use the following: document.body.innerHTML += "<img src..">

Your example would look as follows:

function setcode(code)  {
   document.body.innerHTML += "<img src='empty.gif' onload='function msgbox(msg){alert(msg);};' />";
}

Upvotes: 1

Related Questions