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>
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 want to give users a snippet to put on their own sites which loads a generic javascript file with a unique ID for that user. This is so the content which loads up is dependant on which user id is associated with it.
My best guess so far is something like this:
<script type="text/javascript">
var UID = '';
(function() {
var url = www.test.com/embed.js';
})();
</script>
<noscript>Please enable JavaScript to view this content</noscript>
content powered by <span class="logo">Test</span>
I havent had a lot of luck with this code. Can anyone explain how I should be approaching this please?
Here is the way that google does it. Let me know if you need help applying it:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Ref. https://developers.google.com/analytics/devguides/collection/gajs/
You need to append <script> tag to the DOM.
You should put your entire script inside a single scope (function)
(function(window, uid) {
var document = window.document;
// create your <script> element
var e = document.createElement("script");
e.src = "//my.website.com/my-script.js?user-id=" + window.encodeURIComponent(uid);
// insert it before the very first <script> element already in DOM
var s = document.body.getElementsByTagName("script")[0];
s.parentNode.insertBefore(e, s);
})(window, "some-user-id");
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");
i'm trying to add some html code with javascript and jQuery into a div without an id, but with a class
i'm trying to have it done like this, but without success...
flie.js :
$(".myClassName").ready(function(){
$(this).innerHTML = "<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>";
});
i'm loading the .js file with this html code
.html file :
<div class="myClassName">
</div>
<script>
(function()
{
if (window['ImportFlag'] == undefined || window['ImportFlag'] == void 0) {
var myScript = document.createElement('script');
myScript.type = 'text/javascript';
myScript.src = 'file.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(myScript, s);}
window['ImportFlag'] = 1;
})();
</script>
$(document).ready(function(){
$(".myClassName").html("<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>");
});
You may try like this
<div class="myClassName">
</div>
<script type="text/javascript" src="file.js">
</script>ā
file.js
$(document).ready(function(){
$('.myClassName').html("<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>");
});ā
You should firs ensure that jQuery is loaded BEFORE loading file.js. Then you should use jQuery's functions to set the div inner HTML.
This is a minimalist example :
<html>
<head></head>
<body>
<div class="myClassName">
</div>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script>
(function()
{
if (window['ImportFlag'] == undefined || window['ImportFlag'] == void 0) {
var myScript = document.createElement('script');
myScript.type = 'text/javascript';
myScript.src = 'file.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(myScript, s);}
window['ImportFlag'] = 1;
})();
</script>
</body>
</html>
Then, file.js :
$(document).ready(function(){
$(".myClassName").html("... <span>some text</span>");
});
The jQuery ready() function should be called on the document object, not on an element. It evokes a DOM-ready handler, and can be called using the following syntax (from the official documentation):
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
Matei Mihai and muthu's answers here show you how this works for your example.