I got a request to implement print feature on page, but without opening new window. Instead of classic using of window.open and then window.print methods, all should stay on same page. Only content of one DIV tag should be printed.
After some search on Google I found solutions that use JavaScript, but personally I don’t like the idea to remove content of page to string, print what is neededĀ and then take content back. It’s complicated and it could break something else on page.
Here is better solution to print one DIV only, without JavaScript. I organized HTML like this:
<header> Site header </header <section> Main template section </section> <footer> Site footer </footer> <div id="printDoc"> Div which will be printed </div>
Now, add this CSS:
#printTicket{ display:none; } @media print { header, section, footer { display:none; } #printDoc { display:block; } }
So, the idea is simple. Use @media print in CSS to define what will be shown in print time.
You can even create Print Preview feature on page. With JavaScript or jQuery place DIV on center of the screen. Add Print button which will call window.print(); method to print the window. Of course, only singleĀ DIV will be printed.
Happy coding!