JavaScript print Events

By  on  

Media queries provide a great way to programmatically change behavior depending on viewing state. We can target styles to device, pixel ratio, screen size, and even print. That said, it's also nice to have JavaScript events that also allow us to change behavior. Did you know you're provided events both before and after printing?

I've always used @media print in stylesheets to control print display, but JavaScript provides beforeprint and afterprint events:

function toggleImages(hide = false) {
  document.querySelectorAll('img').forEach(img => {
    img.style.display = hide ? 'none' : '';
  });
}

// Hide images to save toner/ink during printing
window.addEventListener('beforeprint', () => toggleImages(true))
window.addEventListener('afterprint', () => toggleImages());

It may sound weird but considering print is very important, especially when your website is documentation-centric. In my early days of web, I had a client who only "viewed" their website from print-offs. Styling with @media print is usually the best options but these JavaScript events may help!

Recent Features

  • By
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

Incredible Demos

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Element Position Swapping Using MooTools 1.2

    We all know that MooTools 1.2 can do some pretty awesome animations. What if we want to quickly make two element swap positions without a lot of fuss? Now you can by implementing a MooTools swap() method. MooTools 1.2 Implementation MooTools 1.2 Usage To call the swap...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!