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
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

Discussion

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