I am trying use jQuery's rich animation features on dynamically loaded content.
I can dynamically insert script into an element like so:
var element = document.createElement("div");
element.innerHTML = "some html here";
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert("Alert!");';
element.appendChild (script);
The problem occurs when I try to insert jquery code into the script element. This does not work and causes the script to not run at all.
var element = document.createElement("div");
element.innerHTML = "some html here";
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert("Alert!");\n';
script.text = script.text+'$("div").animate({height:300,opacity:0.4},"slow");\n';
element.appendChild (script);
I can successfully append javascript code to change the elements I want, but using jquery functions will simplify things.
With firebug I can see the script elements has been loaded into the dom, however when I add the jquery code to it, nothing happens, not even the alert.
I have included the jquery source file in my main document and wrapped all of my code into a window.addEventListener('load', function()) to call the functions that initiates the code above when the page finishes loading.
Is there a way to dynamically create calls to jquery functions? Am I going about this the right way? I've been stumped for a while and google hasnt solved this one for me, any help is appreciated.
This should do what you want:
$('body').append('<s' + 'cript>console.log("lol");</script>');
But why are you not wrapping your code into a function which you can then call whenever you please?
function iAnimateThings() {
$("div").animate({height:300,opacity:0.4},"slow");
}
hey nothing wrong with your code you just missed one single inverted comma on this line
script.text = script.text+'$("div").animate({height:300,opacity:0.4},"slow")';
here is your working fiddle
http://jsfiddle.net/vYut9/
Related
Can I use insertAdjacentHTML to execute inline javascript?
What works in the browser console:
$('body').append('<script>alert(1)</script>')
What I need to work in browser console:
document.body.insertAdjacentHTML('beforeend', '<script>alert(1)</script>');
The VanillaJS solution does not work. I would be glad about a reason
Using insertAdjacentHTML, although the script tag is added to the page, it won't be parsed or executed.
For the script to actually run you need to use createElement:
var script = document.createElement('script');
script.innerText = "console.log('Hello!');";
document.body.append(script);
var script = document.createElement('script'); // create a new script element
script.innerText = "alert('Hello!');"; // InnerText property html-encodes the content,
document.body.append(script); //append innterText to script
I am trying to use a simple vanilla js script within the page to append some jQuery to the end of the body, where it will come after the jQuery lib load and thus work. I can append js to it fine as shown here..
window.onload = function(){
var script = document.createElement('script');
script.text = "alert('ok');";
document.body.appendChild(script);
};
Attemping to append jQuery:
window.onload = function(){
var script = document.createElement('script');
script.text = "$(window).load(function() {";
script.text += "alert('ok');";
script.text += "});";
document.body.appendChild(script);
};
Works fine appending vanilla, breaks with any jQuery. Why?
*the += instead of one line was one suggested fix to this, but with no luck
**Feels like this should be a duplicate and I'm finding similar issues but not specifically inserting (and triggering, which I realise may be a problem) jQuery.
document.body.innerHTML = "<script>alert(11);</script>"
$("body").html("<script>alert(11);</script>")
innerHTML is not executed.
jQuery html() is executed.
Why so?
Without getting into the theoretical questions of why jQuery chose to do this, the jQuery html() behaves differently than the native innerHTML. By default, jQuery will find the script tags within the HTML, and load then asynchronously. If this behavior is undesirable, you can use $.parseHTML to prevent this from happening by setting the third argument to false.
$("body").empty().append($.parseHTML("<script>alert(11);</script>", document, false));
Note that the script tags will not be added to the DOM using this method.
Conversely, if you wish to achieve the same affect as your jQuery statement in vanilla JS, you can do the following.
var script = document.createElement('script');
script.text = 'alert(11);';
document.body.innerHTML = '';
document.body.appendChild(script);
Try this...
var x = document.createElement('script');
var y = document.getElementsByTagName('script')[0];
x.text = "alert(11);"
y.parentNode.insertBefore(x, y);
Using innerHTML will stop the script from executing according to the documentation in simple words without going into details.
<script type="text/javascript">
var script = document.createElement('script');
script.appendChild(document.createTextNode("alert('11')"));
document.body.appendChild(script);
</script>
This question already has answers here:
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 8 years ago.
The only way to fix it was using google chrome/IE10+ Just can't make it work on IE8.
I'm trying to append some Script to my web page, but i don't want to use any Jquery.
This DOES work, but it make use of jquery on the 3rd line.
var element = document.getElementById("contentSCRIPT");
element.parentNode.removeChild(element); // this removes the div and all the javascript inside it
$('<div id="contentSCRIPT"></div>').appendTo(document.getElementById("main")); // this adds again the content to the page
$('<script>' + document.getElementById("textSCRIPT").value + ' ;</' + 'script>').appendTo(document.getElementById("contentSCRIPT")); // in here i try to add the javascript code back to the content.
I tryied:
var content = document.createTextNode('<div id="contentSCRIPT"></div>');
document.getElementById("main").appendChild(content);
but it adds my script (content) as HTML not code.
any solutions?
Thanks!
Edit:
I have to create the contentScript cuz i want to delete the script from the page and add another multiple times.
I tryied
var contentScript = document.createElement("script");
contentScript.setAttribute("id", "contentSCRIPT");
document.getElementById('contentSCRIPT').innerHTML = document.getElementById('textoSCRIPT').value;
document.getElementById("main").appendChild(contentScript);
But again, this adds the code as an HTML (shows like a label on the page) and don't add to the DOM.
$('<div id="contentSCRIPT"></div>') can be written as follows in javascript:
var contentScript = document.createElement("div");
contentScript.setAttribute("id", "contentSCRIPT");
To do jQuery's appendTo, you want instead to appendChild on the parent:
document.getElementById("main").appendChild(contentScript);
Similarly, for the fourth line:
var script = document.createElement("script");
script.innerHTML = document.getElementById('textSCRIPT').value;
contentScript.appendChild(script);
EDIT
Based on your edited information, you don't need to create the div to hold the contentScript. Simply put an id on the script instead:
var contentScript = document.createElement("script");
contentScript.setAttribute("id", "contentSCRIPT");
contentScript.innerHTML = document.getElementById('textSCRIPT').value;
document.getElementById("main").appendChild(contentScript);
You can create a script element and append it to the document:
var script = document.body.appendChild(document.createElement('script'));
script.text = '/* CODE */';
As a response to your edit: You can remove a script element from the DOM, but you can't remove the script itself.
A live demo at jsFiddle.
var script = document.createElement("script");
var contentScript = document.createElement("div");
contentScript.setAttribute("id", "contentSCRIPT");
script.innerHTML = document.getElementById('textSCRIPT').value;
contentScript.appendChild(script);
You can add a script tag programatically by simply adding the script tag:
var scriptTag = document.getElementsByTagName("head")[0].appendChild(document.createElement("script"));
scriptTag.innerHTML = document.getElementById("textSCRIPT").value;
Change "head" to "body" if you want to add the script to the body.
In fact during a JS script I change the innerHTML attribute of a DIV, and
this content itself contains JS code.
The problem: This code is not executed js on the page.
If you want to execute some javascript after the page loads, you need to insert it in the head of the document:
var script = document.creatElement('script');
script.src = "path to some script";
script.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script);
or to use eval()