سؤال

How can I make an alert popup if the width of the page is less than 1200px, and made responsive?

Thanks!

هل كانت مفيدة؟

المحلول

You can use something like the breakpoints module. Then you setup a breakpoint to trigger at 1200px and show a dialog and either add a css class that changes the layout, or use straight javascript to make the changes.

breakpoints(1200, function(oldPoint, newPoint) {
  alert('The screen width just changed');
});

if you just wanted native jQuery:

$(window).resize(function() {
  var width = $(window).width();
  if (width < 1200){
    alert('Your screen is too small');
  }
});

For completeness, heres the CSS media query (still doesn't take care of the alert, but can help with making the website "responsive").

/* some normal style */
.myclass {
  font-size: 22pt;
}

/* alter the style when the screen's smaller */
@media screen and (max-width: 1200px) {
  .myclass {
    font-size: 18pt;
  }
}

نصائح أخرى

For future Googlers, a 2019 solution is to use JavaScript's window​.match​Media(). It is supported in all major browsers and IE 10 onwards.

You can use it like this:

if (window.matchMedia('(max-width: 1200px)').matches) {
    // functionality for screens smaller than 1200px
}

To make this responsive, you just need to wrap it in a resize function:

$(window).resize(function() {
    if (window.matchMedia('(max-width: 1200px)').matches) {
        // functionality for screens smaller than 1200px
    }
});

This is arguably the most easiest way to check a screen size and it doesn't bloat the code.

Check the Mozilla docs about match​Media to learn more and this one for more info on Testing media queries programmatically.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top