Implement actions for screen width less than 960 px
Here's the brief version of executing code when screen width goes below 960px using window.matchMedia
:
Screen width detection explained
Effective screen width detection is key to creating responsive designs that enhance user experiences. It's crucial to understand the differences between the various methods for determining screen width to ensure cross-device compatibility and precise measurements.
The battle of widths: Window vs Screen
Here's your most common screen width candidates for detection:
window.innerWidth
measures the viewport including the scrollbar if it's visible.screen.width
provides the actual resolution of the screen, not just the browser window.
In the context of responsive designs, window.innerWidth
or $(window).innerWidth()
in jQuery, are preferred since they reflect the exact space available for rendering the webpage.
Synergy of CSS and JavaScript
While CSS media queries are essential for adapting the visual style, pair them with JavaScript for executing more dynamic responses to screen size. Here's the gist:
Don't forget, when listeners have served their purpose, give them some rest with $(window).off()
or mq.removeListener(handleWidthChange)
to avoid memory leaks.
Responding to dynamic size changes
In a responsive run, the show must go on not just on initial load but also as the window size changes or device orientation switches. The resize event saves the day:
Now, to avoid burning your CPU, consider throttling or debouncing your resize events to reduce the frequency of your function executions.
Practical implementation tips
Lightweight coding through conditional loading
Maintaining a lean codebase is key to high performance. Only load resources or initialize scripts if the media query matches:
Ensuring browser compatibility
Ensure wide support for window.innerWidth
and window.matchMedia
- handle the exceptions for older browsers. Consider feature detection libraries like Modernizr for fallbacks.
Avoiding common pitfalls
- Prevent an infestation of infinite loops or redundant actions in your resize event.
- Flags can indicate if an action has already been fired, avoiding needless repetition.
- For easier maintenance, use CSS classes to add/remove styles, not inline styles.
Was this article helpful?