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
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

Incredible Demos

  • By
    Highlighter: A MooTools Search & Highlight Plugin

    Searching within the page is a major browser functionality, but what if we could code a search box in JavaScript that would do the same thing? I set out to do that using MooTools and ended up with a pretty decent solution. The MooTools JavaScript Class The...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Discussion

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