how to insert javascript code via jquery? - javascript

<div id="example">
</div>
<script type="text/javascript">
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$("#example").append(data);
}
function get() {
var content = $("#example").html();
alert(content);
}
</script>
INSERT
GET
</body>
</html>
what i want to do:
when i click on insert, i want to insert this code into example div:
<script type="text/javascript"> function test() { a = 5; }<\/script>
when i click on get, i want to get that code, which i inserted there.
but when i click on insert, and then on get, there's no code.. where is problem ? thanks

According to your comment to Adam Bellaire, you want the script tag to display as normal text. What you are looking to do is encode the text with HTML entities, this will prevent the browser from processing it as normal HTML.
var enc = $('<div/>').text('<script type="text/javascript"> function test() { a = 5; }<\/script>').html();
$("#example").append(enc);

This works:
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$('#example').text(data);
}
function get() {
var content = $('#example').text();
alert(content);
}

Are you checking for the code by browsing the live version of the DOM, using a tool like Firebug? If you are expecting to see your code rendered in your regular browser window, you won't, because the script tags are actually parsed when they are inserted, and script tags aren't visible elements in an HTML page.

Related

Alternate / Equivalent of jQuery.load in pure JavaScript? [duplicate]

I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>

How can I populate an embedded website form with URL parameters using Javascript?

I have a Zoho form embedded on a Squarespace site and I need to populate some fields with URL parameters in Javescript. I'm using the following code to get the parameters:
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
and then to set the parameters to variables:
var campaign1 = getUrlVars()["campaign"];
alert(campaign1);
So that gets the parameter named 'campaign' in the url and assigns it to 'campaign1'. The alert is just to show that it is working, and it is. Then I want to run this:
<script type="text/javascript" src="https://forms.zohopublic.com/....j7Q?campaign="+campaign1 id="ZFScript"> alert(campaign1); </script>
But no matter what I do I can't get that part to reference the variable in the 'src=' section, but I can reference it in the 'alert(campaign1);' immediately after.
I also tried this, which was meant to save the whole URL to a variable named 'site' and just run 'src=site', but that didn't work either.
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1
</script>
<script type="text/javascript"
src=site id="ZFScript"> alert(site);</script>
Your issue is that you are trying to write some js code where it is not parsed/rendered/executed.
The js code will be executed inside <script> tags or onEvent attributes. For instance onclick or onload.
So what you want to do is execute some js code inside a script tag that will generate a script tag with the dynamic src attribute you are trying to achieve. This is a way of doing it:
<script type="text/javascript">
// [...]
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1;
// create a script node
var scriptElement = document.createElement('script');
// set its src attribute
scriptElement.setAttribute('src', site);
// add you new script node to your document
document.body.appendChild(scriptElement);
</script>

Run Function in original page from window.open javascript

how can I run Function in original page from window.open
original_page.html
<div id="Processing" style="display:none;">
<button onclick="window.open("Processing_window.html")">open</button>
</div>
<script language="JavaScript">
function submit_form() {
var upgradeForm = document.getElementById('upgradeForm');
setTimeout("upgradeForm.submit()",3000);
}
</script>
========
Processing_window.html
<script language="JavaScript">
function Processing_window() {
var doc = window.opener.document, Processing = doc.getElementById("Processing");
Processing.style = '';
submit_form(); //Here the problem
window.close();
}
setTimeout ("Processing_window()",5000);
</script>
========
I went to run "submit_form();" funcion from Processing_window.html
To access functions from the opener, use window.opener.functionName, assuming both are in the same domain.
function Processing_window() {
var doc = window.opener.document, Processing = doc.getElementById("Processing");
Processing.style = '';
// Here's the solution
window.opener.submit_form();
window.close();
}
setTimeout ("Processing_window()",5000);
You need to HTML encode the quotation marks in the code in the attribute, or use apostrophes:
<button onclick="window.open('Processing_window.html')">open</button>
As long as the page that you open has the same origin (same server, same protocol), you can use the opener property to access the parent windows window object. There's where you find the reference to the function:
window.opener.submit_form();
You can, but not cross-domain. Only in the same domain.
<script>
function new_win_fun() {
var wind = window.open("Processing_window.html");
var upgradeForm = wind.document.getElementById("upgradeForm");
wind.setTimeout("upgradeForm.submit()",3000);
}
</script>
<button onclick="new_win_func()">Run</button>

Get content inside script as text

I would like to print the content of a script tag is that possible with jquery?
index.html
<script type="text/javascript">
function sendRequest(uri, handler)
{
}
</script>
Code
alert($("script")[0].???);
result
function sendRequest(uri, handler)
{
}
Just give your script tag an id:
<div></div>
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
</script>
​
http://jsfiddle.net/UBw44/
You can use native Javascript to do this!
This will print the content of the first script in the document:
alert(document.getElementsByTagName("script")[0].innerHTML);
This will print the content of the script that has the id => "myscript":
alert(document.getElementById("myscript").innerHTML);
Try this:
console.log(($("script")[0]).innerHTML);
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:
var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
script_text=scripts[i].text;
if(script_text.trim()!==""){ // local script text
// so something with script_text ...
}
else{ // external script get with src=...
$.when($.get(scripts[i].src))
.done(function(script_text) {
// so something with script_text ...
});
}
}
The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.
var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);
The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).
EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.
Printing internal script:
var isIE = !document.currentScript;
function renderPRE( script, codeScriptName ){
if (isIE) return;
var jsCode = script.innerHTML.trim();
// escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
if (textsToEscape) {
textsToEscape.forEach(textToEscape => {
jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "&lt")
.replace(/>/g, "&gt")
.replace("// _ESCAPE_START_", "")
.replace("// _ESCAPE_END_", "")
.trim());
});
}
script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:
let localScript = document.currentScript;
setTimeout(function(){
renderPRE(localScript)
}, 1000);
</script>
Printing external script using XHR (AJAX):
var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
// Exmaple from:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
console.log( this.responseText );
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();
*DEPRECATED*: Without XHR (AKA Ajax)
If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="import" href="autobiographical-number.js">
...
</head>
<body>
<script>
var importedScriptElm = document.querySelector('link[rel="import"]'),
scriptText = scriptText.import.body.innerHTML;
document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
</script>
</body>
</html>
This is still experimental technology, part of web-components. read more on MDN

Changing popup content

I'm opening a popup using popup = window.open(....) and then trying to insert some html into a div in the popup.
popup.document.getElementById('div-content').innerHTML = "hello world"; doesn't do anything however, popup.document.getElementById('the-field').value = "Hello There"; changes the content of a field with an id="the-field".
Any idea why one is working but not the other? How can i replace the content of the div?
hope you can help.
EDIT:
the popup
<!DOCTYPE html>
<html>
<head>
<title>Report</title>
<meta charset="utf-8">
</head>
<body>
<header>
</header>
<div id="div-content"></div>
<div id="report-container">
<input type="text" id="the-field" name="the_field"/>
</div>
<footer>
</footer>
</body>
</html>
the code
function reportComplete(report_content)
{
var popup;
var template_path;
template_path = base_url + "application/views/secure/reports_preview.php";
popup = window.open(template_path, "Report", "scrollbars=yes ,resizable=yes");
popup.document.getElementById('the-field').value = "Hello There"; // this works
popup.document.getElementById('div-content').innerHTML = "hello world";
}
...or simply:
<script type="text/javascript">
function reportComplete(report_content)
{
var popup;
var template_path;
template_path = base_url + "application/views/secure/reports_preview.php";
popup = window.open(template_path, "Report", "scrollbars=yes,resizable=yes");
popup.window.onload = function() {
popup.document.getElementById('the-field').value = "Hello There";
popup.document.getElementById('div-content').innerHTML = "hello world";
}
}
</script>
I think the problem here is that the document in the popup windows hasn't finished loading when you try to access a part of it. On my machine, neither of the divs can be accessed with the provided code.
If the content you want to insert is fixed, then just do all these changes on the popup page itself so that you can make it happen only when the document is completely loaded. If you need to send some dynamic contents, the easiest approach may be using query strings.
UPDATE:
There is a way to fire up DOM manipulation function only when the popup finishes loading. First, you need a callback function on the main window, and put all the DOM manipulation code there:
window.callback = function(doc) {
doc.getElementById('the-field').value = "Hello there";
doc.getElementById('div-content').innerHTML = "Hello world";
}
Then, simply bind a function call to the body onload event on the popup window:
<script type="text/javascript">
function loaded() {
window.opener.callback(document);
}
</script>
<body onload="loaded();"><!-- body content --></body>

Categories