Explain Codes LogoExplain Codes Logo

Implement actions for screen width less than 960 px

html
responsive-design
media-queries
performance
Alex KataevbyAlex Kataev·Aug 9, 2024
TLDR

Here's the brief version of executing code when screen width goes below 960px using window.matchMedia:

// Shrink-o-meter engaged! if (window.matchMedia('(max-width: 959px)').matches) { // Our secret move in action! } // On the lookout for size changes window.addEventListener('resize', () => { if (window.matchMedia('(max-width: 959px)').matches) { // Code for compact mode } });

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:

// Preparing our media battler const mediaQuery = window.matchMedia('(max-width: 959px)'); function responseToSizeChange(query) { if (query.matches) { // If screen become pint-sized } else { // For oversized screens } } // Deploying listener troops! mediaQuery.addListener(responseToSizeChange); // First strike! responseToSizeChange(mediaQuery);

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:

$(window).resize(function() { if ($(window).width() < 960) { // Code for pint-sized screens } else { // Code for screens on steroids } });

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:

if (window.matchMedia('(max-width: 959px)').matches) { // Only for the screens in diet mode }

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.