I am trying to print a specific content area of my page. My problem is I have created separate CSS file for the content of this print area. But that external CSS is not working (loading) in browser print popup. I am sure file path is correct.
This is how I tried it:
function printReceipt(el) {
var docHead = "<html>\
<head>\
<title></title>\
<link rel='stylesheet' href='css/receipt-print.css' type='text/css' media='print' />\
</head>\
<body>";
var docFoot = " </body>\
</html>";
var docBody = document.getElementById(el).innerHTML;
var defaultBody = document.body.innerHTML;
document.body.innerHTML = docHead+docBody+docFoot;
//document.close();
//window.focus();
//setTimeout(function() {
window.print();
document.body.innerHTML = defaultBody;
//}, 1000);
//return true;
}
UPDATE:
Also check in this way. Problem is sill same.
function printReceipt(el) {
var w = window.open();
w.document.write('<html><head><title></title>');
w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
w.document.write('</head><body >');
w.document.write(document.getElementById(el).innerHTML);
w.document.write('</body></html>');
w.document.close();
w.focus();
w.print();
w.close();
return true;
}
Any ideas and suggestion would be appreciated.
The issue was you were printing the page without waiting for the styles and resources to load.
You should wait for the page to load before trying to print it or you can try using inline styles.
function printReceipt(el) {
var w = window.open();
w.document.write('<html><head><title></title>');
w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
w.document.write('</head><body >');
w.document.write(document.getElementById(el).innerHTML);
w.document.write('<script type="text/javascript">addEventListener("load", () => { print(); close(); })</script></body></html>');
w.document.close();
w.focus();
}
Related
Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
I want to link css file on printing specific div but it dose not get stylesheet on printing area. How can i fix this. Here is my source code:
function print_area(){
var win = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
win.document.write('<html><head><title>Print it!</title><link rel="stylesheet" type="text/css" href="css/thinking_aloud_test - Copy.css" media="print"></head><body>');
win.document.write($("#article_main_wrapper").html());
win.document.write('</body></html>');
win.print();
win.close();
}
var win = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
var html = '<html><head><title>Print it!</title><link rel="stylesheet" type="text/css" href="css/thinking_aloud_test - Copy.css" media="print"></head><body>';
html += $("#article_main_wrapper").html();
html += '</body></html>';
win.print();
win.close();
win.document.write(html); // You need to append the `html` in a single element
// Write it at once to a single win.document.write
Here is an example of injecting css via javascript.
(function(d, s, id) {
var css, icss = d.getElementsByTagName(s)[0] || d.getElementsByTagName('head')[0];
if (d.getElementById(id)) {
return;
}
css = d.createElement(s);
css.id = id;
css.href = "http://getbootstrap.com/dist/css/bootstrap.min.css";
css.rel = "stylesheet";
}(document, 'link', 'bootstrap'));
<html>
<head>
</head>
<body>
<button class="btn btn-success">normal button to bootstrap button by adding css</button>
</body>
</html>
if it's for printing with a new tab where you want to append content with css and then print, just go with there steps
var content = document.createTextNode("Some HTML content you want to print");
var css = document.createElement('link');
css.rel = 'stylesheet';
css.type = 'text/css';
css.href = 'css url';
css.media = 'all';
printwindow.focus(); // if its a new tab where you want to do print operation, assuming printwindow is your new tab/popup opened by window.open()
printwindow.document.head.appendChild(css);
printwindow.document.body.appendChild(content);
printwindow.print();
printwindow.document.close();
Another possibility is to read the content of the stylesheet and write it directly into the HTML. Here an example using jQuery:
function print_area(){
var win = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
$.get('main.css', function (data) {
console.log(data);
win.document.write('<html><head><title>my div</title><style>');
win.document.write(data);
win.document.write('</style></head><body >');
win.document.write('<div id="article_main_wrapper">My DIV</div>');
win.document.write('</body></html>');
win.print();
win.close();
});
}
I am going to print an Image (embeded as a property into an object), which retrieved from a WebApi.
So far, I could load the image and show it perfectly on my page like the following:
<img ng-src="data:image/jpeg;base64,{{t.Image}}"/>
However the problem is I don't know how can I print this image?
I have tried out the following listing but I am faced with crashed google chrome page.
var img= window.open($scope.t.Image);
img.print();
Question is How can I print the Image?
This is my Object coming from WebApi:
public class TestImage
{
public string Name { get; set; }
public byte[] Image { get; set; }
}
and the following is how I call the Get method:
$scope.getData = function (val) {
return $http.get('http://localhost:2740/GetData', {
params: {
name: val
}
}).then(function (response) {
$scope.t = response.data;
return response.data;
});
};
********UPDATED********
$scope.imgName = "myImage";
$scope.print = function () {
var printContents = document.getElementById($scope.imgName);
var popupWin = window.open('', '_blank', 'width=300,height=300');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</html>');
popupWin.document.close();
}
<img id="{{imgName}}" ng-src="data:image/jpeg;base64,{{t.Image}}" />
Sorry I misread your question...
Try this ... You will need to assign and ID to the image tag.
$scope.printImg = function(imgName) {
var printContents = document.getElementById(imgName);
var popupWin = window.open();
popupWin.document.open()
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</html>');
popupWin.document.close();
}
I am using the following code for printing a div in a new window:
$('#PrintNews').bind('click', function () {
var approot = '<%=AppRoot %>';
var printContents = new $("#divToPrint").clone();
var myWindow = window.open("", "popup", "width=800,height=600,scrollbars=yes,resizable=yes," +
"toolbar=no,directories=no,location=no,menubar=no,status=no,left=250px,top=80px");
var doc = myWindow.document;
doc.open();
$(printContents).find("#PrintNews").remove();
$(printContents).find("#bottom").remove();
doc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
doc.write("<html>");
doc.write("<head>");
doc.write("<link href='" + approot + "/Themes/print.css' rel='stylesheet' type='text/css' />");
doc.write("<link href='" + approot + "/Themes/secretaryPortal.css' rel='stylesheet' type='text/css' />");
doc.write("</head>");
doc.write("<body style='font: 11pt/1.2 Arial !important;'>");
doc.write("<div class='story'>");
doc.write($(printContents).html());
doc.write("</div>");
doc.write("</body>");
doc.write("</html>");
myWindow.document.close();
myWindow.focus();
myWindow.print();
myWindow.close();
});
});
It does open the print dialog But the page isn't with the original css.
if i change the 4 last lines to:
doc.document.close();
doc.focus();
doc.print();
doc.close();
It opens the page with the right CSS But the print dialog is not opened.
i get an error saying Uncaught TypeError: Cannot call method 'close' of undefined
I have to open it in a new window cause i need to re-size to print dialog, i am aware of #media print
in your description instead of :
doc.document.close();
doc.focus();
doc.print();
doc.close();
use:
myWindow.focus();
myWindow.print();
myWindow.close();
This is the final solution: *Thanks to Yussuf above
$('#PrintNews').bind('click', function () {
var approot = '<%=AppRoot %>';
var printContents = new $("#divToPrint").clone();
var myWindow = window.open("", "popup", "width=800,height=600,scrollbars=yes,resizable=yes," +
"toolbar=no,directories=no,location=no,menubar=no,status=no,left=250px,top=80px");
$(printContents).find("#PrintNews").remove();
$(printContents).find("#bottom").remove();
myWindow.document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
myWindow.document.write("<html>");
myWindow.document.write("<head>");
myWindow.document.write("<link href='" + approot + "/Themes/print.css' rel='stylesheet' type='text/css' />");
myWindow.document.write("<link href='" + approot + "/Themes/secretaryPortal.css' rel='stylesheet' type='text/css' />");
myWindow.document.write("</head>");
myWindow.document.write("<body style='font: 11pt/1.2 Arial !important;'>");
myWindow.document.write("<div class='story'>");
myWindow.document.write($(printContents).html());
myWindow.document.write("</div>");
myWindow.document.write("</body>");
myWindow.document.write("</html>");
myWindow.focus();
myWindow.print();
myWindow.close();
});
I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events