So I have an iframe that's supposed to hold the rendered code from a textarea once a button is pressed, but I'm not sure how to do this in javascript or jquery. I'm aware of how to send a specific site with a URL to display inside a webpage, but for some reason when I try to render the textarea and send it to the iframe, it doesn't work.
this is my iframe:
<iframe id="outputIframe"></iframe>
this is the function I wrote to send contents from textarea editor (this works just fine with a but not with ):
function openIframe() {
var e = document.getElementById('outputIframe');
var editorHTML = editor.getValue();
e.document.innerHTML = editorHTML;
}
So the editor (codemirror) holds the HTML code which users write, and then it should output in the 'outputIframe' iframe element when users press a button. This is similar to the "Try it" sections of w3schools.
function openIframe() {
var editorHTML = editor.getValue();
var iframe = document.getElementById('outputIframe');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(editorHTML);
iframe.contentWindow.document.close();
}
http://jsfiddle.net/tintucraju/2Lsr9ju9/
Using jquery you can type:
$("iframe").contents().find("body").html(yourHTML);
Important to say, this only works if iframe and your parent window are on the same domain, by security reasons.
This will do the trick - just keep in mind that different browsers will accept different maximum lengths of dataURL.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function allByClass(className){return document.getElementsByClassName(className);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('displayBtn').addEventListener('click', onDisplayBtn, false);
}
function onDisplayBtn()
{
var rawInput = byId('htmlInput').value;
var base64Output = "data:text/html;base64," + btoa(rawInput);
byId('htmlOutput').src = base64Output;
}
</script>
<style>
</style>
</head>
<body>
<textarea id="htmlInput" style="width: 462px; height: 185px;"></textarea>
<hr>
<button id='displayBtn'>Display</button>
<br>
<iframe id='htmlOutput' style="width: 462px;"></iframe>
</body>
</html>
Related
I want to access the data returned by this link with a simple function: https://geoapi123.appspot.com/
If you click the link, the return looks like:
function geoip_country_code(){return"UK"}
function geoip_country_name(){return"United Kingdom"}
function geoip_city(){return"London"}
...
In particular, I'm looking for the geoip_city. I do not want to use AJAX or jQuery.
I need a simple function, which does nor require script tags or any references in the head. The data received needs to be stored in a variable, totally independent from the homepage or any events at the homepage. The function cannot be called by any onload or click events, or anything else happening with the homepage.
Here is a working example with head script tag (not what I want):
<head>
<script language="JavaScript" src="https://geoapi123.appspot.com/"></script>
</head>
<body>
<script language="JavaScript">
var city = geoip_city();
alert(city);
</script>
</body>
Here is an idea of what I want:
function getLocation() {
??? //access homepage somehow here
var city = geoip_city(); //get result
alert(city); //alert result
};
getLocation(); //call function
Here is my closest try so far (not working, the return is "0"):
function accessLocation() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", "https://geoapi123.appspot.com", true);
xmlhttp.send();
};
accessLocation();
You can add a script element by code and loading the source from 'geoapi':
function clickHandler() {
var city = geoip_city();
alert(city);
}
function ready() {
var element = document.getElementById('cityFinder');
element.addEventListener('click', clickHandler, false);
}
function init() {
var script = document.createElement('script');
script.onload = function() {
ready();
};
script.src = "https://geoapi123.appspot.com/";
document.getElementsByTagName('head')[0].appendChild(script);
}
<body onload="init();">
<input type="button" id="cityFinder" value="Where am I?"></input>
</body>
I cant seem to understand what I am doing wrong with this I am trying to add in a check box that will target the Iframe created by my predecessor but being a novice to JavaScript I have thus far used snippets of code from various sources to come up with this Frankenstein. I have started courses on java but I'm long off making these codes myself for now.
<b>STATUS TAG</b>
▲
▼
<!--Space--> ||
<!--Refresh page Box-->
<b>Auto Refresh 2Min</b>
<input type="checkbox" name="toggle" value="1" autocomplete="off">
<script>
if (iframeElement.contentWindow.location.hash == "custFrame") {
$("[name=toggle]").prop("checked", true);
pageRefresh = setTimeout(function() {
iframeElement.contentWindow.location.reload();
}, 120000);
}
$("[name=toggle]").click(function() {
if (!$('[name=toggle]').prop('checked')) {
(iframeElement.contentWindow.location.hash = ""
clearTimeout(pageRefresh);
} else {
(iframeElement.contentWindow.location.hash= "custFrame";
pageRefresh = setTimeout(function() {
iframeElement.contentWindow.location.reload()
}, 5000);
}
})
</script>
<!--Space--> ||</p>
<iframe id="custFrame" name="custFrame" src="google.com" marginheight="0" onload="javascript:autoResize(this);" frameborder="0" width="100%" height="80%"></iframe>
<script>
var socket = new easyXDM.Socket({ onReady:
function() { socket.postMessage(document.body.scrollHeight)
}
});
</script>
Inner URLs changed to google for testing
I should mention that I have various Quickbase API commands with the buttons on the top so it must target the frame and cannot revert back to the default url.
This code is completely working for me:
<script type="text/javascript">
// this will run when the document is fully loaded
function init() {
var input = document.querySelector('input[type=checkbox]');
input.onchange=check
function check(){
var start=setTimeout('reload()',3000)
StartStop=input.checked ? start : clearInterval(start)}
}
// this reloads the iframe, and triggers the next reload interval
function reload() {
var iframe = document.getElementById('reloader');
if (!iframe) return false;
iframe.src = iframe.src;
}
// load the init() function when the page is fully loaded
window.onload = init;
</script>
</head>
<body>
<input type="checkbox" id="JustChecked" >checked to get latest<br>
<iframe id="reloader" width="200" height="100" src="test1_frame.html"/>
So, the function "txtLoad()" will not execute while "txtFunc()" is being called by an onLoad function.
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<textarea id="Text" rows="20" cols="70"></textarea>
<script>
function txtFunc(){
var q=1;
}
function txtLoad() {
document.getElementById("Text").innerHTML = "Hello";
}
onload=function(){
txtLoad()
}
onload=function(){
txtFunc()
}
</script>
</body>
</html>
The JavaScript engine says there is nothing wrong with the code inside the "script" element. Does anyone know why the function isn't executing?
your second onload= replaced the function that calls txtLoad, if you want to run both:
onload = function () {
txtLoad();
txtFunc();
};
Also there seems to be extra "}" after the txtFunc.
How can two functions be defined to the onload. For eg:
var x = 1
var x = 2
What do you think the value of x is going to be? Obviously 2.
You are overwriting the onload. Its only going to execute the stuff which you assigned at last.
You could do this to achieve what you want.
onload = init()
function init() {
textLoad();
textFunc();
}
simply because the first onload was overwritten by the las onload.
function txtFunc(){
var q=1;
}
function txtLoad() {
document.getElementById("Text").innerHTML = "Hello";
}
onload=test();
function test()
{
txtLoad();
txtFunc();
}
I'm trying to use a simple string stored in the localStorage functionality built into phonegap as a simple setting to deicide witch set of data to fetch from a server. In the index.html I've been able to save a string from a <select> menu and display it in the header. Using this javascript code:
<script type="text/javascript" charset="utf-8">
window.onload = function() {
document.getElementById("BtnStore").addEventListener("click", storeData, false);
$("#headertitle").append(loadData()).headertitle("refresh");
}
function storeData() {
var e = document.getElementById("klass");
var klass = e.options[e.selectedIndex].value;
localStorage.setItem("klass", klass);
window.location.href = "index.html";
}
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
This appends the stored value in an <h1> element.
But when I from a different html page try to reference the same key from the localstore, nothing is being displayed. Here is that code:
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$("#hejsan").append(loadData()).hejsan("refresh");
};
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
This is also just as a test, appending the string to a <p> element. For some reason nothing is happening, someone knows why?
Thanks
I figured out how to make it work, here is the code i used:
First page:
<script type="text/javascript" charset="utf-8">
window.onload = function() {
document.getElementById("BtnStore").addEventListener("click", storeData, false);
$("#headertitle").html(loadData()).headertitle;
}
function storeData() {
//localStorage.clear();
var e = document.getElementById("klass");
var klass = e.options[e.selectedIndex].value;
localStorage.setItem("klass", klass);
window.location.href = "index.html";
}
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
Second page:
$(document).ready(function() {
function loadData() {
var getKlass = localStorage.getItem("klass");
$("#hejsan").html(getKlass).hejsan;
}
loadData();
}
If anyone else gets stuck! :)
I have a pdf associated with a button . When i click the button i want to get the pdf printed. This is how my button is coded :
<input type="submit" class="btn-red" value="Print"
name="Submit" id="printbtn"
onclick="printPDF('http://www.irs.gov/pub/irs-pdf/fw4.pdf')" />
Now my print functionality works like this :
function printPDF(pdfUrl)
{
if ((navigator.appName == 'Microsoft Internet Explorer') )
window.print(pdfUrl,"_self");
else
{
var w = window.open(pdfUrl,"_self");
w.print();
w.close();
}
}
The problem is , it's working fine in IE and Fire fox , but does not work in chrome. In ie and Firefox, it opens up the xps printer option, but in chrome , it just opens up a new print window, with the print preview of the div and not the pdf . But i want the xps option to be opened up here.
EDIT : In chrome when i try to print , only the html element comes as preview and not the pdf. I am using chrome version : 20.0.1132.57
How can i get around this peculiarity ? kindly help .
This worked for me and didn't require a host HTML file. The key was to wait for onload:
For a link like this:
<a class="print-pdf-link" href="/your/pdf.pdf">Print PDF</a>
I used javascript:
$('a.print-pdf-link').click(function () {
var w = window.open($(this).attr('href'));
w.onload = function () {
w.print();
};
return false;
});
I had to do the same thing and I used a different approach, one that for me worked in both Chrome and Firefox.
My solution involved a print.html helper file, that received the PDF file's url as a GET type parameter, then loaded the pdf inside an iframe. Then it kept checking to see if the pdf had completely loaded (binding the check to the onload event did not work) and on completion it triggered the print method.
Here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<title>Print Page</title>
<meta name="title" content="Print" />
<script>
(function (window, document, undefined) {
var printy = {
urlGET: function (param) {
var params = document.URL.split('?');
if(params.length > 1) {
params = params[1].split('&');
for (var i = 0, len = params.length; i < len; i++) {
if (params[i].split('=')[0] === param) {
return params[i].split('=')[1];
}
}
}
return null;
},
init: function () {
var self = this;
window.onload = function () {
var src = self.urlGET('path');
//creating an iframe element
var ifr = document.createElement('iframe');
document.body.appendChild(ifr);
// making the iframe fill the viewport
ifr.width = '100%';
ifr.height = window.innerHeight;
// continuously checking to see if the pdf file has been loaded
self.interval = setInterval(function () {
if (ifr.contentDocument.readyState === 'complete') {
clearInterval(self.interval);
// doing the actual printing
ifr.contentWindow.print();
}
}, 100);
ifr.src = src;
}
}
}
printy.init();
})(window, document, undefined);
</script>
</head>
<body>
</body>
</html>
This solution is not tested on IE though. We use Macs at work so it was not an option.
In order to do the printing, I use it by calling an URL like this: http://example.com/print.html?path=docs/myfile.pdf