Print a div content using Jquery - javascript

I want to print the content of a div using jQuery. This question is already asked in SO, but I can't find the correct (working) answer.
This is is my HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print'>
</div>
<p>Do not print.</p>
Here I want to print the content of the div printarea.
I tried this:
$("#btn").click(function () {
$("#printarea").print();
});
But it gives a console error when the button is clicked:
Uncaught TypeError: $(...).print is not a function
But when I am trying to print the entire page using
window.print();
it is working. But I only want to print the content of a particular div. I saw the answer $("#printarea").print(); in many places , but this is not working.

Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).
And it is working well...
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
JavaScript
function printDiv()
{
var divToPrint=document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}

https://github.com/jasonday/printThis
$("#myID").printThis();
Great jQuery plugin to do exactly what you're after

If you want to do this without an extra plugin (like printThis), I think this should work. The idea is to have a special div that will be printed, while everything else is hidden using CSS. This is easier to do if the div is a direct child of the body tag, so you will have to move whatever you want to print to a div like that. S So begin with creating a div with id print-me as a direct child to your body tag. Then use this code to print the div:
$("#btn").click(function () {
//Copy the element you want to print to the print-me div.
$("#printarea").clone().appendTo("#print-me");
//Apply some styles to hide everything else while printing.
$("body").addClass("printing");
//Print the window.
window.print();
//Restore the styles.
$("body").removeClass("printing");
//Clear up the div.
$("#print-me").empty();
});
The styles you need are these:
#media print {
/* Hide everything in the body when printing... */
body.printing * { display: none; }
/* ...except our special div. */
body.printing #print-me { display: block; }
}
#media screen {
/* Hide the special layer from the screen. */
#print-me { display: none; }
}
The reason why we should only apply the #print styles when the printing class is present is that the page should be printed as normally if the user prints the page by selecting File -> Print.

None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.
HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p
Javascript:
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}

Without using any plugin you can opt this logic.
$("#btn").click(function () {
//Hide all other elements other than printarea.
$("#printarea").show();
window.print();
});

Below code from codepen worked for me as I wanted,
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
$('button').on('click',function(){
printData();
})
Here is a link codepen

I update this function
now you can print any tag or any part of the page with its full style
must include jquery.js file
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >
JavaScript
function printtag(tagid) {
var hashid = "#"+ tagid;
var tagname = $(hashid).prop("tagName").toLowerCase() ;
var attributes = "";
var attrs = document.getElementById(tagid).attributes;
$.each(attrs,function(i,elem){
attributes += " "+ elem.name+" ='"+elem.value+"' " ;
})
var divToPrint= $(hashid).html() ;
var head = "<html><head>"+ $("head").html() + "</head>" ;
var allcontent = head + "<body onload='window.print()' >"+ "<" + tagname + attributes + ">" + divToPrint + "</" + tagname + ">" + "</body></html>" ;
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write(allcontent);
newWin.document.close();
// setTimeout(function(){newWin.close();},10);
}

First include the header
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script type="text/JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.6.0/jQuery.print.js"></script>
As you are using a print function with a selector which is a part of print.js so you need to call them before you use it...
Else
window.print()
will do it
$("#btn").click(function () {
$("#printarea").print();
});
or
$("#btn").on('click',function () {
$("#printarea").print();
});

use this library : Print.JS
with this library you can print both HTML and PDF.
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>

<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
</div>
<input type='button' id='btn' value='Print' onlick="printDiv()">
<p>Do not print.</p>
function printDiv(){
var printContents = document.getElementById("printarea").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
This Above function should be load on same page.

I tried all the non-plugin approaches here, but all caused blank pages to print after the content, or had other problems. Here's my solution:
Html:
<body>
<div id="page-content">
<div id="printme">Content To Print</div>
<div>Don't print this.</div>
</div>
<div id="hidden-print-div"></div>
</body>
Jquery:
$(document).ready(function () {
$("#hidden-print-div").html($("#printme").html());
});
Css:
#hidden-print-div {
display: none;
}
#media print {
#hidden-print-div {
display: block;
}
#page-content {
display: none;
}
}

Take a Look at this
Plugin
Makes your code as easy as -> $('SelectorToPrint').printElement();

Print only selected element on codepen
HTML:
<div class="print">
<p>Print 1</p>
Click Me To Print
</div>
<div class="print">
<p>Print 2</p>
Click Me To Print
</div>
JQuery:
$('.js-print-link').on('click', function() {
var printBlock = $(this).parents('.print').siblings('.print');
printBlock.hide();
window.print();
printBlock.show();
});

CSS CODE
<style type="text/css">
table {border-collapse: collapse; width: 100%; margin-bottom: 10px; width: 450px;}
table, th, td {border: 1px solid #000000;}
#media print {
.print-btn{
display: none;
}
}
</style>
HTML CODE
<table>
<tbody>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody>
</table>
<button class="print-btn" onclick="window.print()">Print me</button>
OUTPUT

Related

Increment var in td

I am trying to increment a var when I add a new tr
Table
<table id='myTable'>
<tr>
<td id="count"></td>
<td><select><option value="1">1</option></select></td>
<!--obviously some more options-->
</tr>
</table>
<button onclick="addfield()">Add</button>
Script
<script>
var row = 1;
function addfield() {
document.getElementById("count").innerHTML = row;
$("#myTable").find('tbody').append($('<tr>').append($('<td id="count">')).append($('<td><select><option value="1">1</option></select>')));
row++;
}
</script>
What's happening is, that the script is incrementing the first 'td id="count"'-Tag when adding a new 'tr'-Tag instead of incrementing the next 'td'-Tag. Additionally it doesn't show the count in the new generated 'td'-Tag.
What am I missing?
Okay, so first off let me go ahead and say that I blew up your HTML structure because it looks to me like you are using a table to do something that is not tabular, so I changed the structure to be divs. I also took the incrementing out of your script and used CSS counters to get the same effect. if using a table to hold your data is critical after all, then I guess you won't choose this answer.
HTML
<div id="myTable">
<div class="row">
<div class="cellish"><select><option value="1">1</option></select>
</div>
</div>
</div>
<button onclick="addfield()">Add</button>
CSS
body {
counter-reset: count;
}
.cellish {
display: inline-block;
}
.cellish::before {
content: counter(count) " ";
counter-increment: count;
}
JS
function addfield() {
$("#myTable").append($('<div class="row">')).append($('<div class="cellish"><select><option value="1">1</option></select>'));
}
You should not use the same id multiple times in html elements.
Change like this:
$("#myTable").find('tbody').append($('<tr>').append($('<td><select><option value="1">1</option></select>')));

print content of a div except some element in it, doesnt work

I want to print content of a div, and don't want to show some element in this div in print preview, I tried to give noprint class to those element in #media print, but no success! please help!
this is Javascript
<script type="text/javascript">
function PrintPanel() {
var panel = document.getElementById("content");
var printWindow = window.open('', '', 'height=400,width=800');
printWindow.document.write('<html><head><title>DIV Contents</title>');
printWindow.document.write('</head><body >');
printWindow.document.write(panel.innerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
setTimeout(function () {
printWindow.print();
}, 500);
return false;
}
</script>
this is css
<style>
.noprint {
color: red;
}
#media print {
p {
color: green;
}
.noprint {
display: none;
}
}
</style>
and this is html
<body>
<div id="content">
<p>show this, in print preview</p>
<div class="noprint">
dont show this, in print preview!
</div>
</div>
<a id="btnPrint" runat="server" Text="Print" onclick="PrintPanel();" style="cursor:pointer;">print</a>
I provide a sample in jsfiddle:
sample link
Actually the newly created window using window.open does not have any style attached to it.
Here is a snapshot
Style can be added to it by adding inline style in the following code
printWindow.document.write('<html><head><style media="print">' +
'p {color: green;}.noprint {display: none !important;}</style><title>DIV Contents</title>');
i added this code to delete the element before render in the pop up really simple!
This code only get the element by a query like $() of Jquery and is removed from the parent node panel with the method removeChild(element) in this case your div.
var el = document.querySelector('.noprint');
panel.removeChild(el);
https://jsfiddle.net/457vjehs/6/

Changing the background image when clicking on the div?

I am creating a table with div's that already have a background image in them. The classes are "sw", "sl", "so", "sa", "sn", and "su". I made that you could click on the div's and to the right will show the information for that div.
However, I tried adding a hover element to these div's, which work when I do not add the onclick function. With the onclick function, there is no hover that changes the div into a different background image. The background image stays the same when I click on a certain div.
How can you make the background image change when you click on the div?
Here is my HTML code:
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><div class="sw" onclick="show(0)"></div></td>
<td><div class="sl" onclick="show(1)"></div></td>
<td id="info" rowspan="3" style="width:325px;"></td>
</tr>
<tr>
<td><div class="so" onclick="show(2)"></div></td>
<td><div class="sa" onclick="show(3)"></div></td>
</tr>
<tr>
<td><div class="sn" onclick="show(4)"></div></td>
<td><div class="su" onclick="show(5)"></div></td>
</tr>
</table>
And here is my JavaScript code:
function show(num) {
var outputInfo = "";
if(num == 0) {
outputInfo += 'INFO HERE';
}
else if(num == 1) {
outputInfo += 'INFO HERE';
}
...
document.getElementById("info").innerHTML = outputInfo;
}
Oh, and by the way, my background images are used on the CSS portion and all of the classes above share the same image but they were assigned different positions.
Is there a way to show the images as separate backgrounds if another approach to clicking on a div?
Instead of using onclick, maybe try using something Tomm did. I probably encourage you to create a class for all of these id elements. Since you had a shared background image for the original background before the function is clicked, I added background-position. Here is what I did for the script by making a function that I put in the onload of the body (first portion is for backgrounds when clicked, second portion is for original background and will only show for those that are not clicked):
function onloadPage() {
// first portion
$('#sw').click(function() {
$(this).css("background-position", "0 0");
document.getElementById("info").innerHTML = 'INFO HERE';
});
$('#sl').click(function() {
$(this).css("background-position", "0 0");
document.getElementById("info").innerHTML = 'INFO HERE';
});
...
// second portion
$('.classname').on('click', function(e) {
if(!$(e.target).closest('#sw').length) { $('#sw').css("background-position", '0 0'); }
if(!$(e.target).closest('#sl').length) { $('#sl').css("background-position", '0 0'); }
...
}
And then the HTML:
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><div class="classname" id="sw" style="background-position:0 0;"></div></td>
<td><div class="classname" id="sl"></div></td>
<td id="classinfo" rowspan="3" style="width:325px;"></td>
</tr>
</table>
Obviously you will have to adjust your background-positions to the way you need it to look.
Well, your code should looks like:
document.getElementById("info").style.backgroundImage = "url('image.png')";
here I am assuming that info is the id of the div which you want to change background.
This snippet should do. I've linked a couple of random images so you can test it.
By clicking on the div, the info is displayed on the right and that div's background gets updated. By passing the 'this' keyword as argument of the show method you can avoid logics that depend on the div's id.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<style>
.sw{
background-image: url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png");
}
.sl{
background-image: url("https://mdn.mozillademos.org/files/7693/catfront.png");
}
</style>
<script>
function show(num, t) {
var outputInfo = "";
if(num == 0) {
outputInfo += 'This is the information about the image now displayed in div0';
var newUrl='url("http://www.librosweb.es/website/css/images/logo.gif")';
t.style.backgroundImage= newUrl;
}
else if(num == 1) {
outputInfo += 'This is the information about the image now displayed in div1' ;
var newUrl='url("http://www.librosweb.es/website/css/images/logo.gif")';
t.style.backgroundImage= newUrl;
}
document.getElementById("info").innerHTML = outputInfo;
}
</script>
<table width="100%" cellpadding="0" cellspacing="0" >
<tr>
<td style="border: 1px solid red"><div class="sw" onclick="show(0, this)"></div></td>
<td style="border: 1px solid red"><div class="sl" onclick="show(1, this)"></div></td>
<td style="border: 1px solid red" id="info" rowspan="3" style="width:325px;"></td>
</tr>
</table>
</body>
</html>
You can make a simple onclick function in javascript/jQuery ( I use this code with jQuery 1.7.1 ) like the following:
$('#changeMe').on('click', function() {
$('#changeMe').css('background-image', 'url(urlhere)');
})
Where #changeMe is the div id
$('#changeMe').on('click', function() {
$('#changeMe').css('background-image', 'url(http://firefoxzeneize.altervista.org/FirefoxLogo.png)');
})
div{
width : 512px;
height : 512px;
background-image : url("https://www.notebookcheck.net/fileadmin/Notebooks/News/_nc3/20170911_Google_Chrome_logo_vector_download.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="changeMe"></div>

Appending Html Classes To Elements

I asked a question yesterday (Button That When Clicked Will Display Hidden Column in HTML Table). The Name is self-explanatory however, after hours of trying new things and failing I decided to research a different approach. Here is what came up with:
A button that when clicked will append a new class to an element
By doing this, we will toggle a column's visibility by using the 'display' function in css
I have the following HTML element:
echo "<td class =\"development\" id = 'tag$i'>test1</th>";
echo "<td class =\"development\" id = 'tag$i'>test2</th>";
echo "<td class =\"development\" id = 'tag$i'>test3</th>";
$i is the row number so picture each of these <td> being wrapped inside a forloop to create a column.
With Css:
.development{
text-align:center;
padding-left:10px;
display:block;
}
.hide{
display:none;
}
So this is where I will need your help. I propose a button that when clicked will run a JavaScript function that can append the '.hide' class to the td tags.
<button onclick="addCss()">Click me</button>
I am not sure how to write the JavaScript and if I need to pass any parameters such as the id's for the <td> tags.
document.getElementById('yourId').className += ' ClassName'
//To select elements by class name.
document.getElementsByClassName('yourId')
Note: the space after the first ' for the appended class name is important.
Why? : If you have the class name "class1" and append "class2" - It will result in "class1class2"
By adding the space, it will result in "class1 class2" and be recognized as two separate classes.
<button onclick="document.getElementById('yourId').className += ' ClassName';">Click me</button>
If you want to make a better solution.
<script>
function addCss(element) {
document.getElementById(element).className += ' ClassName';
}
</script>
Then just call the function like you originally had. You could even add a parameter for the class name itself.
to override a class document.getElementById("id").className = "newclass";
to add a new class document.getElementById("id").className += " anotherclass";
function addCss(){
document.getElementById("b").className = "hide";
}
function newCss(){
document.getElementById("b").className = "show";
}
body {
font-size: 3em;
background: honeydew;
}
.hide {
display: none;
}
.show {
display: table-cell;
}
<table>
<tr>
<td id=a style="background:skyblue">A</td>
<td id=b style="background:yellowgreen">B</td>
<td id=c style="background:gold">C</td>
<td id=d style="background:orangered">D</td>
</tr>
</table>
<button onclick="addCss()">hide B cell</button>
<button onclick="newCss()">show B cell</button>
Using jQuery, you can add this in the addCss function:
$('td').addClass('hide');

bootstrap "tooltip" and "popover" add extra size in table

Note:
Depending on you Bootstrap version (prior to 3.3 or not), you may need a different answer.
Pay attention to the notes.
When I activate tooltips (hover over the cell) or popovers in this code, size of table is increasing. How can I avoid this?
Here emptyRow - function to generate tr with 100
<html>
<head>
<title></title>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script type="text/javascript" language="javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.1/bootstrap.min.js"></script>
<style>
#matrix td {
width: 10px;
height: 10px;
border: 1px solid gray;
padding: 0px;
}
</style>
<script>
function emptyRow() {
str = '<tr>'
for (j = 0; j < 100; j++) {
str += '<td rel="tooltip" data-original-title="text"></td>'
}
str += '</tr>'
return str
}
$(document).ready(function () {
$("#matrix tr:last").after(emptyRow())
$("[rel=tooltip]").tooltip();
});
</script>
</head>
<body style="margin-top: 40px;">
<table id="matrix">
<tr>
</tr>
</table>
</body>
</html>
thank in advice!
Note: Solution for Bootstrap 3.3+
Simple Solution
In the .tooltip() call, set the container option to body:
$(function () {
$('[data-toggle="tooltip"]').tooltip({
container : 'body'
});
});
Alternatively you can do the same by using the data-container attribute:
<p data-toggle="tooltip" data-placement="left" data-container="body" title="hi">some text</p>
Why does this work?
This solves the problem because by default, the tooltip has display: block and the element is inserted in the place it was called from. Due to the display: block, it affects the page flow in some cases, i.e pushing other elements down.
By setting the container to the body element, the tooltip is appended to the body instead of where it was called from, so it doesn't affect other elements because there is nothing to "push down".
Bootstrap Tooltips Documentation
Note: Solution for Bootstrap 3.0 ~ 3.2
You need to create an element inside a td and apply a tooltip to it, like this, because a tooltip itself is a div, and when it is placed after a td element it brakes table layout.
This problem was introduced with the latest release of Bootstrap. There are ongoing discussions about fixes on GitHub here. Hopefully the next version includes the fixed files.
Note: Solution for Bootstrap 3.3+
If you want to avoid to break the table when applying a tooltip to a <td> element, you could use the following code:
$(function () {
$("body").tooltip({
selector: '[data-toggle="tooltip"]',
container: 'body'
});
})
You html could look like this:
<td data-toggle="tooltip" title="Your tooltip data">
Table Cell Content
</td>
This even works with dynamically loaded content. For example in use with datatables
I would like to add some precision to the accepted answer, I decided to use the answer format for readibility.
Note: Solution for Bootstrap 3.0 ~ 3.2
Right now, wrapping your tooltip in a div is the solution, but it will need some modifications if you want your whole <td> to show the tooltip (because of Bootstrap CSS). A simple way to do it is to transfert <td>'s padding to wrapper :
HTML
<table class="table table-hover table-bordered table-striped">
<tr>
<td>
<div class="show-tooltip" title="Tooltip content">Cell content</div>
</td>
</tr>
</table>
JS (jQuery)
$('.show-tooltip').each(function(e) {
var p = $(this).parent();
if(p.is('td')) {
/* if your tooltip is on a <td>, transfer <td>'s padding to wrapper */
$(this).css('padding', p.css('padding'));
p.css('padding', '0 0');
}
$(this).tooltip({
toggle: 'toolip',
placement: 'bottom'
});
});
If you are using datatable for table then it will be use full
$('#TableId').DataTable({
"drawCallback": function (settings) {
debugger;
$('[data-toggle="tooltip"]').tooltip({
container: 'body'
});
}
});
You should initialize Tooltip inside datatable function fnDrawCallback
"fnDrawCallback": function (data, type, full, meta) {
$('[data-toggle="tooltip"]').tooltip({ placement: 'right', title: 'heyo', container: 'body', html: true });
},
And define your column as below
{
targets: 2,
'render': function (data, type, full, meta) {
var htmlBuilder = "<b>" + data + "</b><hr/><p>Description: <br/>" + full["longDescrioption"] + "</p>";
return "<a href='#' class='Name'>" + (data.length > 50 ? data.substr(0, 50) + '…' : data) + "</a>" +
"<sup data-toggle='tooltip' data-original-title=" + htmlBuilder + ">"+
"<i class='ic-open-in-new ic' style='font-size:12px;margintop:-3px;'></i></sup>";
}
},
If you're using bootstrap directives for AngularJS, use tooltip-append-to-body attribute.
<td ng-repeat="column in row.columns" uib-tooltip="{{ ctrl.viewModel.leanings.tooltip }}" tooltip-append-to-body="true"></td>

Categories