0

I was having the following div in my HTML page:

<div  id="jsmolwindow">
<script type="text/javascript">jmolApplet0 = Jmol.getApplet("jmolApplet0", Info);
</script>
</div>

I would like to create this div at an appropriate moment in one of my external javascript function.

I tried it this way:
var div = document.createElement("div");
div.style.position="absolute";
div.style.float="left";
div.style.top="200px";
div.style.left = "200px";
div.style.width = "150px";
div.style.height = "150px";
var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.src = 'jmolApplet0 = Jmol.getApplet("jmolApplet0", Info);'
div.appendChild(scr);
document.body.appendChild(div);

Nothing happens. I tried to replace scr.src by scr.text but then it tried to execute my script in a new page and failed....

Thanks for you help.

Laetis
  • 1,337
  • 3
  • 16
  • 28
  • 1
    Why append a `script` element with inline code when you're *already* running JavaScript code? Just execute the statement (probably after appending the `div`). – T.J. Crowder Mar 13 '15 at 09:00
  • have a look here, apparently you cannot add a dynamic js -> http://stackoverflow.com/questions/3248384/document-createelementscript-synchronously – Sim1 Mar 13 '15 at 09:00
  • 1
    @SimoneRiboldi: Yes, you can. That question and answer is about synchronously executing an **external** script. – T.J. Crowder Mar 13 '15 at 09:02

1 Answers1

0

Two issues there:

  1. There's no reason to append a script element with inline code when you're already running JavaScript code: Just execute the statement right there in your code (probably after appending the div).

  2. If you really want to append the script element, even though it's not necessary, you set the content of the element to the code to run, not the src property. The src property is a URL of an external script file. You set the content by creating a text node containing the code and appending it to the script element, prior to adding the script element to the document.

But again, #2 is unnecessary and pointless given the code you've shown; just execute the statement.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I see your point. I was trying to stick as much as possible to the actual code (since I am a beginner) and did not see the obvious. Neither the less I still have two issues when executing directly the javascript in my js file: 1) In my html file I am loading a load of js source to execute this script: "" .... how to I proceed now? 2) This script is kind of loading a image and I wanted it in that specific div. Hoe do I do? Thanks – Laetis Mar 13 '15 at 09:17
  • @Laetis: That's a completely different question, and I'm afraid I don't have time to answer it right now. I suggest posting it as a new question, as it's not the same as this one. – T.J. Crowder Mar 13 '15 at 09:21