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!
Page Visibility API
One event that’s always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?
fetch API
One of the worst kept secrets about AJAX on the web is that the underlying API for it,
XMLHttpRequest
, wasn’t really made for what we’ve been using it for. We’ve done well to create elegant APIs around XHR but we know we can do better. Our effort to…
Chris Coyier’s Favorite CodePen Demos II
Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so…
Introducing MooTools Dotter
It’s best practice to provide an indicator of some sort when performing an AJAX request or processing that takes place in the background. Since the dawn of AJAX, we’ve been using colorful spinners and imagery as indicators. While I enjoy those images, I am…
Source link