Printing dynamic content with javascript - javascript

Problem
We have page with form.
User fill the form and submit it.
I need to print page with data from form and some other content.
Code #1
$(document).ready(function($){
$('input[name=sumb_but]').bind('click', function(e){
e.preventDefault();
var print_text = "<p>Test " + $('#form').serialize() + "</p>";
var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
newWin.document.body.innerHTML = print_text;
newWin.print();
});
});
Cool, but:
I need specific css
Print window appear before content was loaded... ooops
Ok!
Code #2
$(document).ready(function($){
$('input[name=sumb_but]').bind('click', function(e){
e.preventDefault();
var print_text = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1251' /> <title>Оформление доверенности (простая письменная форма)</title> <link rel='stylesheet' type='text/css' href='/css/print_forms/warrant.css'> </head> <body> <p>Test " + $('#form').serialize() + "</p></body><script type='text/javascript'>window.print();</script></html>";
var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
newWin.document.write(print_text);
});
});
document.write - in other case css not loading
At the and of content added "window.print()"
That works fine in all browsers, but not in IE - windows with content loading successfully without printing dialog.
I need help!
p.s.
CSS with media="print" - not good solution for this case for some reason.

$(document).ready(function($){
$('input[name=sumb_but]').bind('click', function(e){
e.preventDefault();
var print_text = "<p>Test " + $('#form').serialize() + "</p>";
var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
newWin.document.body.innerHTML = print_text;
newWin.document.body.onload = function() { newWin.print(); }
});
});
this could help

Related

How to append the HTML code snippet to HTML iframe using jquery?

How to append the HTML code snippet to HTML iframe using jquery? Actually, I have added an HTML code snippet in MySQL Database using PHP. Now I have fetched that HTML Code snippet and trying to append that HTML code snippet in iframe using jquery.
$( document ).ready(function() {
var snippets='<?php echo $snippets_preview; ?>';
$(function() {
var $iframe = $('#iframehtml');
$iframe.ready(function() {
$iframe.contents().find("body").append(snippets);
});
});
});
But I am getting the following error
Uncaught SyntaxError: Invalid or unexpected token
snippets_preview has the following value in it. when I change the value of snippet_preview. it works fine.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>'.$postdata['snippets_css'].'</style>
<script>'.$postdata['snippets_javascript'].'</script>
</head>
<body>
'.$ContentDecodedHTML.'
</body>
</html>
If you want to embed html code in an iframe you have to do for example:
JAVASCRIPT (class)
<script>
// -------------------------------------------------------- CLASS
var class_iframe = {
// ------------------------------------- STEP 1 (Create an new Iframe)
generateIframe: function(src, targetDOM){
// ---------------- Create iframe
var newIframe = document.createElement('iframe');
newIframe.onload = function(){
class_iframe.getIframe($('.iframehtml').contents());
};
newIframe.src = src;
newIframe.className = "iframehtml";
newIframe.frameBorder = "0";
// ---------------- Insert iframe in DOM
$(targetDOM).replaceWith(newIframe);
},
// ------------------------------------- STEP 2 (Get iframe in this class)
getIframe: function(iframe){
class_iframe.frame = iframe; console.log(class_iframe.frame);
},
// ------------------------------------- STEP 3 (Append in this iframe)
appendIframe: function(targetInIframe, content){
console.log(class_iframe.frame);
$target = class_iframe.frame.find(targetInIframe); console.log($target);
$target.prepend(content);
},
}
// -------------------------------------------------------- ACTION (loadPage)
$(document).ready(function(){
//$("body").prepend(`<div id="insertIframe"></div>`); //Just for the test
class_iframe.generateIframe("your_url_iframe.html", "#insertIframe");
});
</script>
In your html page
<div id="insertIframe"></div>
JAVASCRIPT (for append in your new iframe)
<script>
// -------------------------------------------------------- ACTION (after loadPage)
class_iframe.appendIframe("html", `<div class="insert">Hello world !</div>`);
</script>

Insert jQuery Object in another browser tab with events

I'm currently trying to copy a div to another browser tab with the events still working.
I found ways to do this on the same tab, but not for a different one, for example:
https://api.jquery.com/clone/
jQuery: clone elements AND events
Here's my approach:
var newWindow;
if (navigator.userAgent.match(/msie|trident/i))
{
newWindow = window.open("", "_blank");
}
else
{
newWindow = window.open("about:blank", "_blank");
}
var currentDate = moment().format(L11n.get(".dateTimeFormat"));
var printDate = L11n.get(".printDate") + " " + currentDate;
var cssUrl = $app.appRoot + "rt/main.css";
var jsUrl = $app.appRoot + "app/main.js";
var d3Url = $app.appRoot + "pub/d3.js";
var title = L11n.get(".contractDetail");
var start = "<!DOCTYPE html> \
<html xmlns=\"http://www.w3.org/1999/xhtml\" style=\"height: 100%;\"> \
<head id=\"Head1\"> \
<title>" + title + "<\/title> \
<link href=\"" + cssUrl + "\" rel=\"stylesheet\" type=\"text/css\" /> \
<script src=\"" + jsUrl + "\" language=\"javascript\" type=\"text/javascript\"></script> \
<script src=\"" + d3Url + "\" language=\"javascript\" type=\"text/javascript\"></script> \
<script src=\"pub/jquery.js\" language=\"javascript\" type=\"text/javascript\" /></script> \
<body class=\"detailTabsView limitWidthPrint\" style=\"margin-bottom: 0; margin-top: 0; height: auto;\"> \
<div class =\"detailPrintHeader\">" + printDate + "</div>\
<div class =\"detailContainer\">";
var end = "<\/div><\/body><\/html>";
newWindow.document.write(start + detailHtmlString + end);
newWindow.document.close();
//newWindow.document.$("#dashboardFrame").replaceWith($(".ALL #dashboardFrame").clone(true));
var dash = $(".ALL #dashboardFrame").clone(true, true);
$(newWindow).load(function ()
{
console.log("loaded");
$(newWindow.document.body).find("#dashboardFrame").replaceWith(dash);
});
$(newWindow.document).ready(function ()
{
console.log("ready");
});
newWindow.focus();
The interesting part is this:
var dash = $(".ALL #dashboardFrame").clone(true, true);
$(newWindow).load(function ()
{
console.log("loaded");
$(newWindow.document.body).find("#dashboardFrame").replaceWith(dash);
});
Further explanation:
I have a webapp that, for example, shows a diagram made with D3 (Data-driven-documents). It also shows other information, split up into a tab pane. That diagram has some datapoints that show a tooltip when the user hovers over them.
The app also has a button that opens the current tab in a new window. The tooltips don't work on that new window, but it would be nice if they would.
Edit:
Simple example:
Tab A = source tab, with a button in it that has a click-event bound to it. The event reads, let's say the current time and writes it to an alert box.
Then I open a new tab with javascript, let's call it Tab B. When Tab B is loaded, I want to append the button from Tab A to the body of Tab B. The event on the button still has to work in Tab B.
TL:DR:
You can only solve this by re-binding the events on the new tab in the
ready event
I tried that with this piece of code. You have to pass the event-handler within that piece of code (sry for the long-line-example). Just copy that snipped into your dev-console, paste and run it. You will get an alert();
var newWindow = window.open('about:blank', '_blank');
newWindow.document.write('<!doctype html><html><head><title>Test</title><script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script><script type="text/javascript">$(document).ready(function() { $(window).load(function(e) { alert(\'onload\'); }); });</script><script type="text/javascript">function onload() {alert("load");}</script></head><body><div>Test</div></body></html>');
newWindow.document.close();
You can't get the event from another tab. That's browser restriction. You can use an iFrame for that.
Edit:
As I said you can use an iFrame to retrieve the loaded message. But it also should be possible within a new tab. There is a window.postMessage method in HTML5. You can see which browsers are supportet on caniuse.com. You may also have a very brief look at David Walsh's site. He explains how to use it.
I do not have ressources right now. But you can simple "google" it. Or test it otherwise within your developer console to access a variable declared in windowA on windowB. The result will be undefined
Edit part 2: I don't think it is possible without having a script-ressource or a inline JavaScript in the DOM.
See example:
<!doctype html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#test_button').bind('click', function (e) {
alert('Button was clicked!');
e.preventDefault();
});
$(window).load(function (e) {
var body = '<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt></head><body id="body">' + $('#test_button').clone(true, true).attr({'id': 'test2_button', 'data-time': new Date()}).wrap("<div />").parent().html() + '</body></html>';
console.log(body);
var newWindow = window.open('about:blank', '_blank');
newWindow.document.write(body);
//newWindow.document.write('<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt></head><body>' + + '</body></html>');
newWindow.document.close();
});
});
</script>
<body>
<div id="test">
<button id="test_button">Test-Button</button>
</div>
</body>
</html>
I just copy the #test_button into the new window. As a new window is opened a new DOM is generated without the JavaScript event (bind) of the #test_button.
If you append the JavaScript for event-handling you can of course copy your hole content into a new tab/window. Just move your event-bindings into a JavaScript file and append it like I did with the jQuery-file.
Furthermore you just can open the new tab programmatically within your existing tab as you can't access the other tabs ressource (DOM).
You can pass a parameter as well if you like. Just add a param to the open. See other SO-question.
If it helped to clearify your question please feel free to mark this one as answer.
Edit 3
I hope I got it right this time! Try this one:
JavaScript-file (e. g. test.js)
$(document).ready(function () {
console.log('ready');
$('#test_button').bind('click', function (e) {
alert('Button was clicked!');
e.preventDefault();
});
})
HTML-file
<!doctype html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(window).load(function (e) {
var body = '<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt><scr' + 'ipt type=\'text/javascript\' src=\'test.js\'></scr' + 'ipt></head><body id="body">' + $('#test_button').clone(true, true).attr({'data-time': new Date()}).wrap("<div />").parent().html() + '</body></html>';
console.log(body);
var newWindow = window.open('about:blank', '_blank');
newWindow.document.write(body);
//newWindow.document.write('<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt></head><body>' + + '</body></html>');
newWindow.document.close();
});
});
</script>
<body>
<div id="test">
<button id="test_button">Test-Button</button>
</div>
</body>
</html>

Open popup in Javascript

I have a js rendered in HTML which would give a preview of the form. The code is functioning correctly but it gives me the output on the same page rather i want to open it in a pop-up window. I have tried using window.open () with no luck. Could you please help me out in how i can use window.open() for the below. The button ID is preview. When the button is clicked it executes a function similar to below
$("#preview").click(function() {
$("#formpreview").delete();
var fieldSet = ...................});
You can populate the html in the child window using the below example:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="button" id="launch" value="Launch Child Window"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
var btnLaunch = document.getElementById("launch");
btnLaunch.onclick = function () {
var childWindow = window.open("", "", "height=500, width=500");
var html = "";
var theVariable = "Conent in Child Window";
html += "<p>" + theVariable + "</p>";
childWindow.document.body.innerHTML = html;
}
Store the popup as a variable, then set the popup's HTML to whatever you need.
$("#preview").click(function() {
var myWindow = window.open("", "Popup", "width=300, height=500");
myWindow.document.write("<html>This is where your content goes</html>");
});

How to make the output of multiple JavaScript functions display in HTML?

So I'm trying to display the results of a few function calls in a JavaScript file that uses benchmark.js in a separate HTML file.
My js file looks something like this (disregard the names of methods and classes):
class.init(function(context) {
Benchmark("function description", {
'defer': true,
fn': function(deferred) {
var x = context.ones([100, 100]);
var y = x.repeat(2, 0);
context.barrier(function (){
deferred.resolve();
});
},
'onComplete': function(event) {
//This is what I'd like to print out
console.log(this.name + ": " + (this.stats.mean * 1000).toFixed(2) + " ms");
//
}
}).run();
There are multiple function calls similar to this.
My HTML just looks something lile:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> Sublime Webpage </title>
</head>
<body>
<div class="main">
<div class="head">
<h1>Hello</h1>
</div>
<script src="filename.js"></script>
</div>
</body>
</html>
At the moment, it just prints the results to the console, which is better than nothing, but obviously not what I want. I talked to someone briefly and they suggested I use jQuery. I looked into it, and tried using document.write(this.name + ": " + (this.stats.mean * 1000).toFixed(2) + " ms") in the place of console.log(), but this didn't seem to work. Does anyone have suggestions?
Use document.createTextNode:
// add an output div to your html
<div id='output'></div>
// in your benchmark code
var output = document.getElementById('output');
output.appendChild(document.createTextNode('some result'));
Fiddle

Reading <input> values from an iframe and sending it to another as HTML

How should I read values from iframe1 and send it to iframe2 as HTML? Either JavaScript or jQuery is acceptable - it does not matter. I'm new to javascript. I already found code like the one below, maybe this will help.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function getIframeText() {
var iframe0 = document.getElementById("iframe0");
var iframe0document=iframe0.contentDocument||iframe0.contentWindow.document;
var inputIframe = iframe0document.getElementById("frame_text");
alert(inputIframe.value);
}
</script>
</head>
<body>
<div>
<button onclick="getIframeText()">get iframe text</button>
<iframe id="iframe0" src="test.html" >
<input type=text id="parent_text">
</div>
</body>
</html>
Take a look to this: http://jsfiddle.net/nick_craver/c5JeU/2/
$('button').click(function(){
var fjq = $('#frame')[0].contentWindow.$;
var f = $('#frame').contents().find('#data');
f.append( '----------<br>');
f.append( 'test1: ' + fjq.data(f[0], 'test1') + '<br>test2: ' + fjq.data(f[0], 'test2') + '<br>' );
f.append( 'test3: ' + typeof (fjq.data(f[0], 'test3')) + '<br>' );
})
I found it on: Access jQuery data from iframe element

Categories