I want to add a element into the existing DOM to have the javascript code run.
I did this with YUI:
var scriptNode = Y.Node.create('<script type="text/javascript" charset="utf-8">alert("Hello world!");<\/script>'); var headNode = Y.one('head'); headNode.append(scriptNode);
It's successfully added to the DOM but it doesn't give me an alert.
Someone knows what the problem is?
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
The “script” tag JavaScript programs can be inserted almost anywhere into an HTML document using the <script> tag. You can run the example by clicking the “Play” button in the right-top corner of the box above. The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag.
You have two options: You could include raw HTML <script> tags in your Markdown, or you could use MkDocs' extra_javascript setting to point to your own JavaScript file.
I have no idea how YUI's Node.create()
function works, so no comment on that. But a simple cross-browser script is:
window.onload = function() { var s = document.createElement('script'); s.type = 'text/javascript'; var code = 'alert("hello world!");'; try { s.appendChild(document.createTextNode(code)); document.body.appendChild(s); } catch (e) { s.text = code; document.body.appendChild(s); } }
The try..catch block is necessary as most browsers like the first method but some don't and throw an error. The second method covers those. You can also simply eval the code, which is more or less equivalent and what some libraries do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With