I'm creating a page which is suppose to be a little interactive. The user is suppose to be able to change a bunch of information by checking off an checkbox.
Index.php:
<span id="changeIt">Deactivated! - [ChangeMod]<img src="pic/deactivated.png"></span>
<form action="">
<input type="checkbox" id="checkboxChange" onclick="ChangeEverything();">Change Everything!</input>
</form>
<script TYPE="text/javascript" SRC="script/map_checkbox.js"></script>
map_checkbox.js:
var checkbox6 = document.getElementById("checkboxChange");
var posting6 = document.getElementById("changeIt");
var script = document.createElement("scriptChange");
function ChangeEverything(){
if (checkbox6.checked){
posting6.innerHTML="Activated! - [ChangeMod]<img src='pic/activated.png'>" ;
script.src = 'scriptMain.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(scriptChange);
}
else{
posting6.innerHTML="Deactivated! - [ChangeMod]<img src='pic/deactivated.png'>" ;
script.src = 'scriptSec.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(scriptChange);
}
}
Is it possible to overwrite the script like this, or do I have to use another method?
i think you have a problem with the
var script = document.createElement("scriptChange");
tou have to put the tag NAME
var script = document.createElement("script");
Related
I know how to insert a standard script to the body or header (changing .body or .header) depending on the case with:
document.body.appendChild(document.createElement('script')).src = 'https://url.com';
But I have a script that I need to insert into the header but it contains a var and Iām not sure how I should insert it.
<script type="text/javascript"> var _iub = _iub || []; _iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; </script> <script type="text/javascript" src="//cdn.iubenda.com/cs/iubenda_cs.js" charset="UTF-8" async></script>
Any ideas?
You can create a script element and add the content with .innerHTML, afer just insert to body (or header).
var script = document.createElement('script');
script.innerHTML = ` var _iub = _iub || []; _iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; `;
document.body.appendChild(script);
I'm setting up some editors with HTML, CSS and JS code. The code of each of them is reloaded in an iframe when it's change. HTML and CSS code reloads perfectly, bus the JS code that is injected inside of a script in the body of the iframe is not working, possible because it's not rerunning once it's updated, but I don't know how to do it...
Any idea?
Here's an example in Plunker http://plnkr.co/edit/tpl:8rFfZljYNl3z1A4LKSL2?p=preview
HTML
<div class="result">
<!-- RESULT -->
<style id="style"></style>
<script id="script"></script>
<script id="jQ" type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<iframe id="view" class="view"></iframe>
</div>
JS
var app = angular.module('plunker', []);app.controller('MainCtrl', function($scope) {
var style = document.getElementById('style');
var script = document.getElementById('script');
var jQ = document.getElementById('jQ');
var view = document.getElementById('view');
var viewDocument = view.contentDocument || view.contentWindow.document;
var body = viewDocument.getElementsByTagName('body')[0];
var head = viewDocument.getElementsByTagName('head')[0];
var widgets = [];
var loadScript = document.createElement('script');
loadScript.innerHTML = "var $ = parent.$; console.log('loaded');";
$scope.html = '<div id="test">Testing</div>';
$scope.js = 'console.log("More test");';
head.appendChild(jQ);
head.appendChild(loadScript);
head.appendChild(style);
body.appendChild(script);
$scope.$watch('html', function(nv){
body.innerHTML = nv;
body.appendChild(script);
});
$scope.$watch('js', function(nv){
script.innerHTML = nv;
});});
Note: Code seems to run fine when is set by hand
SOLVED:
I found a way around. Here's the code in case someone else need it
setTimeout(updatePreview(codeHTML, codeCSS, codeJS), 300);
function updatePreview(codeHTML, codeCSS, codeJS) {
var view = document.getElementById('view');
var viewDocument = view.contentDocument || view.contentWindow.document;
var codeHTML = (codeHTML === undefined) ? '' : codeHTML;
var codeCSS = (codeCSS === undefined) ? '' : codeCSS;
var codeJS = (codeJS === undefined) ? '' : codeJS;
viewDocument.open();
viewDocument.write('<style type="text/css">' + codeCSS + '</style>');
viewDocument.write('<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>');
viewDocument.write(codeHTML);
viewDocument.write('<script type="text/javascript">' + codeJS + '</script>');
viewDocument.close();
}
This is called in $scope.$watch of de editors passing the updated value.
Weave: http://kodeweave.sourceforge.net/editor/#b6b39c95ec91f42950957a1ac8dc707f
I see you were able to solve your problem however I have a minor suggestion.
If a user uses setTimeout or setInterval like so...
setInterval((function() {
return $('body').css('background', newGradient())
}), 1000)
The problem you have in your code is it will add to the original literation and your setInterval function in this case will be added to the previous one.
Thus a good idea is to create the iframe dynamically and add the code within that. This way you have more control over what's being added to the iFrame and how to handle it.
document.querySelector(".preview").innerHTML = ""
var frame = document.createElement("iframe")
frame.setAttribute("id", "preview")
frame.setAttribute("sandbox", "allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts")
document.querySelector(".preview").appendChild(frame)
I need to place an entire javascript function in a div and show it for testing purposes, how can I accomplish this? I am doing this from code behind in asp.net
EDIT
<!-- Facebook Conversion Code for Website Purchase -->
<script type='text/javascript'>
(function() {
var _fbq = window._fbq || (window._fbq = []);
if (!_fbq.loaded) {
var fbds = document.createElement('script');
fbds.async = true;
fbds.src = '//connect.facebook.net/en_US/fbds.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(fbds, s);
_fbq.loaded = true;
}
})();
window._fbq = window._fbq || [];
</script>
Edit: You need to do some trickery: How to show <div> tag literally in <code>/<pre> tag? Which says that you need to escape your < and > characters in your tag to < and > for them to show in the <pre>. The example below has been modified to show this.
You should try using the html <pre> tag, it's commonly supported and does exactly what you're asking for:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
<pre>
<script type="text/javascript">
console.log('hi');
</script>
</pre>
should show something like
<script type="text/javascript">
console.log('hi');
</script>
I want to add script tag using javascript, but I am not able to get it work. Below is code. I want to add this code in bigcommerce cart page.
var duration = document.getElementsByName("cartdata");
var cartstr = '<!-- MyBuys Page Parameters ā Place in <body> element -->';
cartstr += '<script type="text/javascript">';
cartstr += 'mybuys.setPageType("SHOPPING_CART");';
cartstr += 'mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->';
cartstr += 'mybuys.set("amount","99.34");';
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
cartstr += 'mybuys.addCartItemQtySubtotal("'+n[0]+'","'+n[1]+'","'+n[2]+'");'+'<br>';
}
cartstr += '</script>';
cartstr += '<!-- End MyBuys Page Parameters -->';
//alert(cartstr);
var script = document.createElement("script");
script.type = "text/javascript";
script.text = cartstr; // use this for inline script
document.body.appendChild(script);
I want below code added to page:
<!-- MyBuys Page Parameters ā Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
This demonstrates how to dynamically add JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var optionalFunctionLoaded = false;
var commonFunction = function() {
console.log("test button clicked " + (new Date()).toLocaleString());
if (!optionalFunctionLoaded) {
// get optionalSrc e.g. via AJAX, eventually providing actual input values
var optionalSrc = 'function optFun(){console.log("optional function");}';
// if optionalSrc is not empty
var script = document.createElement("script");
script.innerHTML = optionalSrc;
document.head.appendChild(script);
optionalFunctionLoaded = true;
}
if(optionalFunctionLoaded) optFun();
}
</script>
</head>
<body>
<button id ="testButton">test</button>
<script type="text/javascript">
document.getElementById("testButton").onclick = commonFunction;
</script>
</body>
</html>
Tested with Firefox 24.0 / Linux.
The solution is to just add the code to the page:
<!-- MyBuys Page Parameters ā Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
Why use JavaScript to put it there? Just add it to the page. You might have to adjust it a bit with your loop:
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
You should just be executing the code, there is no need to build the string. In the end, what you are trying to do is the same thing as running the code! Just execute it.
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com");
mybuys.set("amount","99.34");
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
I don't know why would you want to do that. But if you really want to, here is a way you could try.
$('body').append("console.log('blah');")
OR
$('body').html($('body').html()+"console.log('blah');")
Replace console.log('blah') with your code
Note this is assuming you are using JQuery.
If not, you can still use Native Javascript to do something similar. Just search for creating an element and adding it to another using vanila javascript and you'll get lots of information on google.
Although, as epascarello says, its not a good idea to do this. Its basically a code smell and you can improve your code.
Hope this helps.
This question looks a little dumb... but I am wondering if is it possible to insert in-line javascript code into another javascript code. Lets put this clear:
I'm trying to put a google plus button, appending it through jquery as follows:
jQuery('.gplus').append('<g:plusone annotation="inline"></g:plusone>');
This button needs external js in order to work properly. What i'm trying to do is insert the external js doing this:
var gplusjs = '
<script type="text/javascript">
(function() {var po = document.createElement("script");
po.type = "text/javascript"; po.async = true;
po.src = "https://apis.google.com/js/plusone.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(po, s);
})();
</script>';
jQuery('#js').append(gplusjs);
The result of this is the code printed as HTML, but not interpreted as a script.
This is possible? I am a dumbass? Thanks!
That's because jQuery append and scripts don't work. Do it the old fashioned way
var gplusjs = '(function() {var po = document.createElement("script");po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(po, s);})();';
var script = document.createElement("script");
script.textContent = gplusjs;
document.head.appendChild(script);
Also note that multi line string literals don't exist in JS.
You should just execute that code normally:
var po = document.createElement("script");
po.type = "text/javascript"; po.async = true;
po.src = "https://apis.google.com/js/plusone.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(po, s);
Or, even easier:
$.getScript("https://apis.google.com/js/plusone.js");