Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something if screen width is less than 960 px

How can I make jQuery do something if my screen width is less than 960 pixels? The code below always fires the 2nd alert, regardless of my window size:

if (screen.width < 960) {
    alert('Less than 960');
}
else {

    alert('More than 960');
}
like image 203
Evanss Avatar asked Sep 26 '22 02:09

Evanss


2 Answers

Use jQuery to get the width of the window.

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}
like image 515
aziz punjani Avatar answered Oct 22 '22 11:10

aziz punjani


You might want to combine it with a resize event:

 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});

For R.J.:

var eventFired = 0;

if ($(window).width() < 960) {
    alert('Less than 960');

}
else {
    alert('More than 960');
    eventFired = 1;
}

$(window).on('resize', function() {
    if (!eventFired) {
        if ($(window).width() < 960) {
            alert('Less than 960 resize');
        } else {
            alert('More than 960 resize');
        }
    }
});

I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.

like image 151
jk. Avatar answered Oct 22 '22 12:10

jk.