Javascript overwrites data on screen and refreshes page - javascript

I have been working on a project that I just need to print the contents of a hidden div. The below solution works fine, but replaces the page contents with the div then calls the print of the window and then replaces the page with the original contents. This is fine, but when I click on the page after this or try to print again, the page refreshes.
Is there a way, without opening a new window to print the contents of a div and the page still be functional?
$scope.printDiv = function(printable) {
var restorePage = document.body.innerHTML;
var printContent = document.getElementById(printable).innerHTML;
document.body.innerHTML = "<html><head><title></title></head><body>" + printContent + "</body>";
window.print();
document.body.innerHTML = restorePage;
};

I had created a directive that did something much like this. It involves creating a new window, populating it with the HTML you want printed, printing that window, and then finally closing.
The code looks like the following:
$scope.printPage = function() {
var pageToPrint = $window.open('', 'Print Page', 'width=800, height=600');
pageToPrint.document.write(angular.element(pageHtml).html());
pageToPrint.document.close();
pageToPrint.focus();
pageToPrint.print();
pageToPrint.close();
}
This works in all of the browsers and cleanly closes everything out once the user finishes with the print dialog window.

You can do it with CSS: https://stackoverflow.com/a/356123/1516112
When the user click on your button, wrap your entire page inside a div using the .no-print class. Next add your content in another div next to the previous div. Call print() and restore your page. It should works.

See a similar question that I found: AJAX - Print Page Content
It seems the answer of Matt Razza is what You are looking for.
If you're trying to print invisible content you could use two
different css files for the different media (screen vs print) where
you hide/unhide the required content via display: none; and then
spawn the print dialog via window.print().
<link rel="stylesheet" type="text/css" href="theme1.css" media="screen" />
<link rel="stylesheet" type="text/css" href="theme2.css" media="print" />
<div class="hidden_on_page">YOU CAN'T SEE ME BUT YOU CAN PRINT ME!</div>
<div class="on_page">YOU CAN SEE ME BUT YOU CAN'T PRINT ME</div>
Then in theme1.css:
.hidden_on_page { display: none; }
theme 2.css:
.on_page { display: none; }
And you would trigger the print dialog to spawn when required via:
window.print();

Related

open iframe src to new page

My web page opens app.html first.After clicking to login i need to open index.html which i open in iframe and i dynamically create iframe in javascript.so to open that i frame im appending to document.body.But it appends to the body of the app.html.But I need to open in new page
var el = document.createElement("iframe");
el.setAttribute('id', 'ifrm');
el.setAttribute('name', 'ifrm');
el.setAttribute('src', '/index/index.html');
el.setAttribute('width', '100%');
el.setAttribute('height', '100%');
el.setAttribute('scrolling', 'no');
document.body.appendChild(el);
You could use this to open in a new window:
var myWindow = window.open("/index/index.html");
You would have to layer the iframe over the current page
el.style.position = 'absolute';
el.style.top = 0;
el.style.left = 0;
You question is a bit unclear as to what you are trying to do. The answer all depends on things like:
Are you trying to open index.html in addition to app.html or instead of it?
If you want both open, then do you want to open in a new window?
If so, do you want a regular window (i.e. same size as the original, without modification). Yes, then use JavaScript:
newWin = window.open("index.html", "My App's Main Window", winOptions);
or a specific size window, with other modifications (no Navigation bar, No address bar, etc) - in other words do you want a Popup Window
<html>
<head>
<title>JavaScript Popup Example</title>
<script type="text/javascript">
function loginCheck(){
//isLoggedIn is a boolean variable you've set to check login
if (isLoggedIn) {
popup();
}
}
function popon(){
var winOptions = "";
winOptions += "location=1, ";
winOptions += "status=0, ";
winOptions += "scrollbars=0, ";
winOptions += "width=100, ";
winOptions += "height=100";
newWin = window.open(
"index.html",
"My App's Main Window",
winOptions
);
newWin.moveTo(400, 300); //300 pixels down,
//400 pixels to the right
}
</script>
</head>
<body onload="javascript: loginCheck()">
<h1>JavaScript Popup Example</h1>
</body>
</html>
Or do you want to open index.html in a new tab?
simply use the target attribute in your anchor tag with the value set to new, e.g. <a target="new"...
If you are trying to replace index.html/open in the same tab... you don't need to do anything with your href
If you want to open the content of app.html WITHIN the app.html page somehow... then you either:
Need to use an iframe (that can already be tagged in the app.html (you don't need to create it dynamically with JavaScript) and load index.html into it OR...
Use AJAX to load the page behind the scenes while app.html is STILL loaded, in the window/tab... without reloading or replacing it. Once the AJAX request completes, youi would then do something with the HTML from index.html... like:
use plain vanilla JavaScript to dynamically create a div (or show a hidden div) and fill it once index.html is loaded.
use a (jQuery) widget such as a tab/tab set or accordion and fill it when app.html is loaded

Refresh a div on the same page after using click function

I'm using a JavaScript print function that print's the predefined div of a page on click. The function is as following:
<head>
<script type="text/javascript">
function printDiv(any printable div) {
var printContents = document.getElementById(any printable div).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
</head>
The printer form input method and printable div are as following:
<body>
<input type="button" class="button" onclick="printDiv('any printable div')" name="print" value="print" />
<div id = "any printable div"> On button click contents here are printed </div>
</body>
I'm also using a jQuery text marquee / scroller on the same page that performs it task based on the function:
$(document).ready(function(){
All works fine independently. The problem is that the text marquee / scroller stops scrolling the text when the print button is clicked. The scroller can't scroll the text until the page is refreshed. So I'm using html meta refresh but that may be an annoying experience to the visitors. I don't want to use the scroller in an iframe too.
I've tried some jQuery and JavaScript based solution by this time. The scripts refresh (Just fades in and out the whole block of texts) the div where the scroller is silently but actually can't keep the text scrolling.
Is there any good jQuery or JavaScript based solution available that refreshes the scroller div silently based on the situation I explained above in a given period of time?
You cannot have spaces in your variable name. function printDiv(any printable div) is a syntax error.
Try instead:
function printDiv(elId) {
var printContents = document.getElementById(elId).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
I assume from what you've stated that the intention here is to be able to print only a certain div, rather than an entire page. If that is the case then you are really going to extremes here to perform this function.
If you just want to make a prettier version of the page to print (one without menus, etc) look at How can I have different CSS when I print or print preview?. That question will show how to use a different set of css for printing, so you can set display:none; to anything that you don't want to display when printing.
If you want to print only a single div then you could look at the jQuery print element plugin. This is a simple js file that you link in your html then call
$([selector]).printElement();
to print just that element. Eg you could rewrite your method as so:
function printDiv(anyPrintableDiv) {
$('#' + anyPrintableDiv).printElement();
}

javascript nullifies when setting the document.body.innerHTML

Good day.
I am currently working on a project that prints a desired <div> to a printer.
Here is the code:
var printContents = document.getElementById(id).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
document.body.style.display = "none";
window.print();
document.body.innerHTML = originalContents;
document.body.style.display = "block";
This code works and prints the desired <div>, but after that I need to put back the previous page again so I used this statement:
document.body.innerHTML = originalContents;
document.body.style.display = "block";
This displays the previous page but the functionalities of my buttons are gone?! Can someone explain to me what happened and is there a solution to this problem? Thanks in advance!
This is happening because you've wiped out the old DOM which had events wired up to it, and replaced it with a totally new, different DOM that just happens to have the same HTML.
Presumably you're taking this approach because the printable zone is determined at runtime. A less-destructive solution might be to create a new <iframe> and copy the desired markup into that; then invoke print() on the iframe. Something like:
var printElement = function(element) {
var frame = document.createElement('iframe');
document.appendChild(frame);
frame.contentDocument.innerHTML = element.innerHTML;
frame.contentWindow.print();
document.removeChild(frame);
};
You'll also need to copy over any CSS references into the <iframe>.
(note this is pseudo-code and not tested)
Your code clears the document and then puts back the HTML stored in originalContents, but this variable stores only a string, so all previously registered event handlers are gone.
Why don't you create a print stylesheet and hide everything except the content that you want to print?
<link rel="stylesheet" type="text/css" href="print.css" media="print">
When you reset the innerHTML, you don't get all your event handlers back. They are wiped out when you create entirely new DOM elements.
One idea would be to have two master divs in the body, one that is your normal display and one that is what you want to print. You can then hide whichever one you don't want to display like this:
<body>
<div id="mainContent">main screen content goes here</div>
<div id="printContent">generated print content goes here</div>
</body>
// hide main content
var mainDiv = document.getElementById("mainContent");
mainDiv.style.display = "none";
// put content to print in the print div and show it
var printDiv = document.getElementById("printContent");
printDiv.innerHTML = document.getElementById(id).innerHTML;
printDiv.style.display = "block";
// print
window.print();
// restore visibility
mainDiv.style.display = "block";
printDiv.style.display = "none;
You could also just use the whole body for printing and use a stylesheet with media="print" to control the visibility of the things you do/don't want to print.
You can add a click event to all dives inside your page so that user can click the div.
after that add a class to that div which the class is defined within the print CSS file.
inside css print file use the following code:
`*{display:none}
.printableDiv{display:block}`
to define a print css file use this code :
<link rel="stylesheet" type="text/css" href="print.css" media="print"> (which Rafael has told you ).
good luck

IE7 & IE8 javascript print function

I'm having a javascript issue I can't figure out. I've taken a snippet of code that I got
here and am using it in this page.
The idea is that users can click the 'Print List' button and the listing is copied to a div within a hidden iframe and printed. The printed page contains the the iframe source HTML with the list inserted properly. However, in IE7 & 8, the printed page is the full parent page, not the iframe. The behavior in IE9, Chrome and FF is correct.
I tried debugging the script but I couldn't see where it was going wrong.
Here's the code that the Print List click triggers:
function printSection(id) {
if (document.getElementById('print_frame').contentDocument){
theIframe = document.getElementById('print_frame').contentDocument;
}
else {
theIframe = document.frames['print_frame'].document;
}
var thePrinter = theIframe.getElementById('print_section');
var theCopy = document.getElementById(id);
thePrinter.innerHTML = theCopy.innerHTML;
parent.print_frame.printPage();
}
And here's the printPage() function:
function printPage() {
window.parent.print_frame.focus();
window.print();
}
I'd appreciate any help. Please let me know if you need more information. Thanks so much.
A simpler solution might just be to use CSS media types to hide the content of the page and show an otherwise hidden element for print.
CSS
.print{display:none;}
#media print {
.pagecontainer{display:none;}
.print{display:block;}
}
HTML
<body>
<div class="pagecontainer">
Page content here
</div>
<div class="print">Only show this when printing</div>
</body>

Hide document body on page load

I have a javascript that is loaded in the document head that needs to hide the document body until all page contents have loaded. I have tried:
$(document.body).hide();
But there still appears to be a flicker in some browsers. I am using the latest jQuery library (1.6.2). Firing the event on domready does hide the document body, but causing a flicker as well.
All that I can control is what is in the javascript. I cannot manipulate the static html pages as the script is being developed as a plugin.
Hiding content until the page is loaded is an anti-usability feature. Some parts of the content may take while to load, meanwhile your visitors see nothing. Browsers render content as it is received because users chose that as the preferred model in the very begining.
If you persist with this approach, you must hide the content using script. Otherwise, users with javascript disabled or not available, or where the script fails to execute correctly, will never see the content.
The simplest way to hide content using script is to use document.write to create a style sheet, then remove it to show the content:
document.write( '<style class="hideStuff" ' +
'type="text/css">body {display:none;}<\/style>');
window.onload = function() {
setTimeout(
function(){
var s, styles = document.getElementsByTagName('style');
var i = styles.length;
while (i--) {
s = styles[i];
if (s.className == 'hideStuff') {
s.parentNode.removeChild(s);
return;
}
}
}, 1000); // debug pause
}
The best way to do this is to put all content in a container div and have a style sheet that hides it by default. You can then show the content once everything is loaded. There is no way to run Javascript before the default page content renders so the only way to start out hidden is with a statically defined CSS rule:
HTML:
<body>
<div id="container">
all dynamic page content goes here
</div>
</body>
CSS in a stylesheet with the page to make it initially not visible:
#container {display: none;}
And, then you can do whatever you want with javascript and when you're done building the page, you do this to make it visible:
document.getElementById("container").style.display = "block";
or in jQuery:
$("#container").show();
You can use CSS and JS:
In the top of your document, below the TITLE use CSS:
<style type="text/css">body {visibility: hidden;}</style>
And after this use JS to restore the visibility:
<script type="text/JavaScript">
document.write('<style type="text/css">body {visibility: visible;}</style>');
</script>
Enjoy :)

Categories

Resources