printing contents in a new tab prints a blank page - javascript

I am trying to print the contents of a div to a new tab, however, it print a blank page only for the first time. When i manually print the page, it works fine. I am loading 2 tables wrapped in a div.
HTML structure:
<div class="receipt_bg" id="print_receipt">
<div id="div1">
table1
</div>
<div id="div2">
table2
</div>
</div>
<button type="button" id="print_btn">Print</button>
Javascript:
$('#print_btn').click(printClick);
function printClick(receipt_bg) {
var DocumentContainer = $('.receipt_bg').html();
var WindowObject = window.open("PrintWindow","_blank");
WindowObject.document.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">'+ '<html><head><title>test print receipt</title> <link href="../css/style.defaultprint.css" rel="stylesheet" type="text/css" /></head><body>' + DocumentContainer + '</body></html>')
setTimeout(WindowObject.print(), 5);
WindowObject.close();
}
I even tried using
WindowObject.onload = WindowObject.print();
instead of
setTimeout(WindowObject.print(), 5);
still it doesn't seem to work. I saw a similar post, but its solutions did not work for me.

Check this url.
It contain few example for printing content from page.It has all you need.
I had use jQuery Print Element 1.2 for print, in this, if you have large content to print then you need to increases time out from 50 to 500,other wise it will show blank page as you face issue, but for me it is only happend in Chrome browser, other then that i haven't face this issue.
check printElement js. below url contain nice example with demo and source.
Check this : jQuery Print Page Options
Here is the code , which will help you.
function printClick(receipt_bg) {
var DocumentContainer = $('.receipt_bg').html();
var WindowObject = window.open("", "printElementWindow", "width=650,height=440,scrollbars=yes");
WindowObject.document.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">'+ '<html><head><title>test print receipt</title> <link href="../css/style.defaultprint.css" rel="stylesheet" type="text/css" /></head><body>' + DocumentContainer + '</body><script type="text/javascript">setTimeout(printPage(),1000); function printPage(){focus();print();}<\/script></html>')
WindowObject.close();
}
This will work for you, here i added one javascript function to your window code, which will executed after timeout. try it, and let me know , is it work for you or not. you can extend or decrees timeout as per your content.

Related

Prevent browser from partially rendering the page while the document is being loaded [duplicate]

This question already has answers here:
How can I make the browser wait to display the page until it's fully loaded?
(16 answers)
Closed 4 years ago.
Both Firefox and Chrome is rendering my pages way too early, which results in my a couple of frames where you first see the header, then the content, and then the footer. It's a very very unpleasant page loading experience.
The way I get around this right now is this, which is such a silly workaround I would like to avoid. It also causes the page to flash white in Chrome.
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<div id="render-all-at-once" style="opacity:0; min-height:100%;">
content
</div>
<script>
document.getElementById("render-all-at-once").style.opacity = 1;
</script>
</body>
</html>
The problem is basically this:
<script>
function sleep(millis) {
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while (curDate - date < millis);
}
</script>
<div>
This will be rendered in the first frame.
</div>
<script>
sleep(3000);
</script>
<div>
And only after that first frame has been rendered will you see this line. You don't see the first line for 3 seconds as
you might, but you do see it flash, right before both lines are displayed.
</div>
<!---
I would like the browser to not render anything until
the entire entire document has been processed.
--->
In isolated tests, the above code seem to work as expected - both lines will be rendered at the same time after 3 seconds. But as soon I start adding a couple of random style-sheets to the page, the problem starts occurring.
I can't seem to narrow it down to any particular style-sheet or style. I can't figure out what's causing it. I've both tried loading all styles sheets from , or just having all of them inlined in a style element. This doesn't make any difference. I'm testing this using Chrome as it seems to happen more frequently there.
Does anyone have any experience with this sort of problem, or have any ideas what's causing it, and know of any way to prevent it?
What I like to do is wrap my content in a div and set it to display:none.
Then, I defer my CSS loading and in my CSS file, and set that wrap div to display:block.
I also compress all my CSS files into one single file (for better loading).
<!DOCTYPE html>
<html>
<head>
<style>
.wrap {
display: none;
}
</style>
</head>
<body>
<div class="wrap">
content
</div>
<noscript id="deferred-styles">
<link rel="stylesheet" type="text/css" href="compressed.css" />
</noscript>
<script>
var loadDeferredStyles = function() {
var addStylesNode = document.getElementById("deferred-styles");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement);
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if(raf) {
raf(function() {
window.setTimeout(loadDeferredStyles, 0);
});
} else {
window.addEventListener('load', loadDeferredStyles);
}
</script>
</body>
</html>
Use the network tab in developer tools to see the process & response of each request. First, the HTML is fully received and parsed by the browser which then looks for remote objects to load top-down: stylesheets, images, javascript, etc.
So, to have complete control over how things appear, send an HTML document that looks exactly as you'd like the initial view to be (ex: a blank white document, achieved with inline CSS or a <style> tag that targets <body>). Then use a line of Javascript to listen for the load event and update your display, for example:
<!doctype html>
<html>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/stackoverflow/primary.css">
<body style="display: none;">
<h1>Headline</h1>
</body>
<script>
window.addEventListener("load", function(event) {
document.querySelector("body").style.display = "block";
});
</script>
</html>

Javascript OpenWindow not loading stylesheet not working

I have a document with a table and Print button. The print button calls a javascript function to generate a printable version in a new window. The printable version should load a stylesheet from the site. However the stylesheet does not load. And when I open the source from the newly opened window, although the stylesheet href -appears- correct, clicking on it does nothing. So clearly my browser doesn't recognise it as a proper href.
SO: Why is the link tag not being recognised as an href?
Here is the javascript function:
jQuery("div.jch-noise_records span.print_button a").on('click', function(e) {
e.preventDefault();
var getpanel = document.getElementById("jch-noise_records");
var MainWindow = window.open('', '', 'height=500,width=800');
MainWindow.document.write('<!DOCTYPE html>\r\n');
MainWindow.document.write( '<html lang="en-US">\r\n<head>\r\n');
MainWindow.document.write( '<title>Noise Records Report</title>\r\n');
MainWindow.document.write( '<link rel="stylesheet" href="http://example.com/wp-content/plugins/jchwebdev-noise_by_hour/jchwebdev-noise_by_hour.css" type="text/css" media="all" />\r\n');
MainWindow.document.write( '</head>\r\n');
MainWindow.document.write( '<body>\r\n');
MainWindow.document.write( getpanel.innerHTML);
MainWindow.document.write( '\r\n</body>\r\n</html>\r\n');
MainWindow.document.close();
MainWindow.document.focus();
// MainWindow.print();
return true;
});
And here is a bit of the html generated in the print window:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Noise Records Report</title>
<link rel='stylesheet' href='http://example.com/wp-content/plugins/jchwebdev-noise_by_hour/jchwebdev-noise_by_hour.css' type='text/css' media='all' />
</head>
<body>
<span class="close"><a title="Close" href="#">X</a></span><div class="jch_table_wrapper"><p class="header"><span class="report_date">2018-06-12 18:00</span><span class="report_title">Noise By The Hour (Checkbox Detail)</span><span class="report_ip">71.231.25.83</span></p><p class="header"><span class="report_query">For date >= 2018-01-01 AND date <= 2018-05-31</span></p><table id="jch-noise_by_hour" class="jch-noise"><tbody><tr class="total"><td colspan="5">Total of <span>151 </span> days tracked for <span></span> at <span> 12AM</span> from <span>01/01/2018</span> to <span>05/31/2018</span><br>
Average noise: <span>82.8dbA</span><br>
Total # of events detected: <span>12,153</span><br>
Average number of events/hour: <span>6</span></td></tr>
</tbody></table></div>
</body>
</html>
Although I'm guessing at why this is the issue, I wanted to put this answer here for visibility as it seems to have worked based on the comments on the question.
I believe the new popup window (or new tab depending on the user's settings) is not loading and rendering the linked CSS due to some sort of security/context issue.
Since the window.open(url, name, params); call you are making is passing in an empty string for the url and the name parameters I believe this is setting your new window to be in a different "protocol" or "domain" context than your opening page, AND the linked CSS file.
Someone like #EricLaw might be able to confirm this suspicion but I believe that "" (empty string), "about:blank", and "javascript:" trigger some special ~sandboxing~ when used for popups/iframes.
That all said, it appears that if you set the URL of your initial window.open() call to be an actual HTML page (it can be a dummy/stub) from your server... and then afterwards inject the CSS link you want and content to render in the body... it overcomes this issue.

"Updating" webpage through jQuery and localStorage

So I have a home page that I created using HTML. I run it off my computer by opening the HTML file. I'm trying to add a feature that allows me to edit it from the page (using content-editable or append), not the source code. To achieve this, I came up with using localStorage to hold the updated version of the webpage, and loading the page from that updated version. See here. (Theoretically, I would periodically update the source code from the localStorage version so it's all matched up.)
However, when I tried it, my page won't update. I have a version saved into localStorage, but it seems as if the program can't overwrite the that version, or something similar.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>SCSS | Projects</title>
<link type="text/css" rel="stylesheet" href="home page heading style.css">
<link type="text/css" rel="stylesheet" href="home page projects style.css">
<script type="text/javascript" src="save script.js"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body onload="checkEdits()">
<div id="everything">
<div class="box">
<div class="img"><img src="who am i.png" /></div>
<div class="wrapper">
<div class="title">Who Am I?</div>
<div class="description">A project for English class describing who I am through different medias and explained by unit questions.</div>
</div>
<div class="notes" contenteditable="true">Complete.</div>
</div>
S
</div><!--End everything-->
</body>
My JavaScript looks like this:
function saveEdits() {
//get the editable element
var edited = document.getElementById("everything");
//get the edited element content
var userVersion = edited.innerHTML;
//save the content to local storage
var localStorage.Edits = userVersion;
}
function checkEdits() {
//find out if the user has previously saved edits
if(localStorage.Edits != null)
document.getElementById("everything").innerHTML = localStorage.Edits;
}
But my page doesn't actually work right; it doesn't load the updated version. From viewing localStorage, it seems as if it's not even saving it properly.
Why doesn't it work? How can I fix it? Is there something conceptually incorrect about my plan? Any help would be appreciated; thanks!
For localStorage you can get/setItem e.g.
function saveEdits() {
//get the editable element
var edited = document.getElementById("everything");
//get the edited element content
var userVersion = edited.innerHTML;
//save the content to local storage
localStorage.setItem('Edits', userVersion);
}
function checkEdits() {
//find out if the user has previously saved edits
var savedEdits = localStorage.getItem('Edits');
if (savedEdits != null) {
document.getElementById("everything").innerHTML = savedEdits;
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Storage
You might also notice that jQuery is not used/required for this code...

Javascript print div not working in Safari

I have a Javascript function that prints the contents of two elements in a webpage. It works in Chrome, Firefox and IE but Safari just brings up an empty window and if I select print, it simply prints a blank page.
Here's my code:
var content = "<!doctype html><html><head>";
content += '<link rel="stylesheet" href="/css/normalise.css" type="text/css" />';
content += '<link rel="stylesheet" href="/App_Themes/CS2011/StyleSheet.css" type="text/css" />';
content += "</head><body>";
//Find the div to insert the rest of the html after
var contractToFind = $(divElement).parent().find("div").get(0);
//Insert rest of code
content += contractToFind.innerHTML;
content += "</body></html>";
//Set up print window and print
var printWindow = window.open('', '', params);
printWindow.document.write(content);
printWindow.document.close();
printWindow.focus();
printWindow.print();
//Close the window
printWindow.close();
Is there a way I can modify my code to allow it to render the page properly in Safari so I can print it? Preferably without using additional plugins.
Edit: Thanks Eric but that didn't work for me. Adding a time delay to the print seems to work well although it's not ideal, even a 10ms delay solves the issue. The line I used was:
setTimeout(this.print, 100);
I found a solution to this problem. The problem resides in the fact that window.print() is not standard for all browser and Safari probably takes a different approach on when triggering it.
I changed a little your code so maybe this solution can't fit your possibility but it works for all browser (tested on Safari, FF, Chrome, IE8).
Note that you need to have a different page for the popup content (I changed the code to retrieve the contract to make a sample for myself, hope you will figure out how to get contract content).
The code:
HTML for the page that opens the popup
<body>
<input type="button" id="popup" value="Open Popup" />
<div id="yourContract">
<div>blablabla</div>
<div>blablabla2</div>
<div>blablabla3</div>
<table>
<tr>
<td>blablabla td1</td>
<td>blablabla td2</td>
</tr>
<tr>
<td>blablabla td3</td>
<td>blablabla td4</td>
</tr>
</table>
</div>
</body>
<script>
$("#popup").click(function(){
var win = window.open("static.html");
});
</script>
HTML for the popup (static.html):
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$.holdReady(true);
$.getScript("print.js", function() {
$.holdReady(false);
});
</script>
</head>
<body>
<script>
var contract = window.opener.$("#yourContract").html(); //change to fit your needs
$("body").html(contract);
</script>
</body>
</html>
JS file (print.js) called by static.html
$(document).ready(function(){
window.print();
window.close();
});
How does it works:
static.html consists of two script section. The section in the body loads via javascript the content in the page.
The section in the head prevent the document to trigger ready status by setting holdReady to true. Then it loads print.js which waits for document to be ready, but we will decide the exact moment because we are preventing it.
After the script is included in the page holdReady is set again to false, triggering the ready status to document and calling the print() and close() functions on the window.
This however occurs after the browser has loaded all the page content, so you will see the preview in the popup page and the print dialog.
Hope this solution is what you need.

How to use JS to jump to a specific place in a page? Tried scrollIntoView, not working

I have a PHP form for discussions. Each message has its own response button, which is dynamically generated. I'm using javascript in the button to make a response form visible at the bottom of the page, but I can't for the life of me get the page to jump down to the form once it's visible. This is a problem for pages that have a lot of discussions on it, as some users may not know to scroll down and will just think the button didn't work.
Here's what I have now for my button code:
<img src="images/reply.jpg" border=0 />
The changeVisibility function looks like this:
function changeVisibility(parentID, elementID) {
document.getElementById(elementID).style.visibility="visible";
document.forms[0].parent_id.value=parentID;
var el = document.getElementById(elementID);
el.scrollIntoView(true);
}
In my form, I have a div whose id is set to responseForm. When clicking the button, the div does become visible, but the scrollIntoView is not working - I have to manually scroll down to see it. Any ideas?
Use window.location.hash
function changeVisibility(parentID, elementID) {
document.getElementById(elementID).style.visibility="visible";
document.forms[0].parent_id.value=parentID;
window.location.hash = '#' + elementID;
return false;
}
<img src="images/reply.jpg" border=0 />
EDIT: I think the issue before was that you weren't returning false, so the default action (going to #) was still occurring.
OK, I finally found something that works. I've been doing what I was taught to do in the Stone Age: when using javascript calls in what needs to be a link, use
a href="#" onClick="yourFunction()"
Apparently it's the # that's killing things for me; if I just use
a href="javascript:yourFunction()"
it works correctly. This may or may not be considered good practice anymore, but it works.
User window.location.hash to redirect to an ID/anchor. E.g.
HTML:
<p id="youranchor">bla bla</p>
JavaScript:
window.location.hash='youranchor';
EmmyS - This code does work. Here's a complete example for you:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Some title</title>
<script type="text/javascript">
function jumpToParagraph() {
window.location.hash='paragraphjump';
}
</script>
</head>
<body>
<p onclick='jumpToParagraph();'>Jump to the paragraph at the end! [version 1]</p>
<p>Jump to the paragraph at the end! [version 2]</p>
<p style="height: 1500px;">Some nonsense</p>
<p id="paragraphjump">You made the jump</p>
</body>
</html>
Put it into a file and test the file in your browser.
Hmm, you could try using document.body.scrollTop = document.getElementById(elementId).offsetTop; (not tested)
Hum, the following JavaScript code works like a charm:
<script type="text/javascript">
function scrollToPos() {
var el = document.getElementById("abc");
el.style.visibility = "visible";
el.style.display = "block";
el.scrollIntoView(true);
}
</script>
When clicking this link scroll<br />
the following div get's gets visible and scrolls into view (tested in IE6, IE8, FF3.6.3, Google Chrome 4.1 and Opera 10.5, all on windows)
<div id="abc" style="height:100px;color:red;font-weight:bold;visibility:hidden;display:none;">
abc
</div>

Categories

Resources