Cross browsers detect print events using javascript
Here I'm explain about detecting before print, after print in cross browsers using Java script.
Window beforeprint,afterprint events working in only IE,Firefox browsers, but we can detect these events using matchMedia with event handler, here I'm explain with small example.
(function () {
var beforePrint = function () {
alert('Functionality to run before printing.');
};
var afterPrint = function () {
alert('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
<div class="noPrint">
<input type="button" value="Print" onclick="javascript: window.print();" />
</div>
<div class="yesPrint">
print content
</div>
<style media="print">
.noPrint{ display: none; }
.yesPrint{ display: block !important; }
</style>
Below is the out put of the above code:
We tested in chrome and IE browsers
matchMedia supports in below showing browsers
I think it is useful post at the time of print using javascript.
Thanks...
Window beforeprint,afterprint events working in only IE,Firefox browsers, but we can detect these events using matchMedia with event handler, here I'm explain with small example.
Javascript Code:
(function () {
var beforePrint = function () {
alert('Functionality to run before printing.');
};
var afterPrint = function () {
alert('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
HTML Code :
<div class="noPrint">
<input type="button" value="Print" onclick="javascript: window.print();" />
</div>
<div class="yesPrint">
print content
</div>
CSS :
<style media="print">
.noPrint{ display: none; }
.yesPrint{ display: block !important; }
</style>
Below is the out put of the above code:
We tested in chrome and IE browsers
matchMedia supports in below showing browsers
I think it is useful post at the time of print using javascript.
Thanks...
Comments
Post a Comment