272

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');
}
Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
Evanss
  • 23,390
  • 94
  • 282
  • 505
  • 2
    Are you doing this when the page load or is it when you resize browser. Its always a good idea to say alert(screen.width) to see whats been used to decide. – Farrukh Subhani Oct 10 '11 at 15:31
  • 1
    Why not [media queries](http://www.css3.info/preview/media-queries/)? – bzlm Oct 10 '11 at 15:32
  • 3
    Why not media queries? I can think of any number of cases where media queries would be of no assistance whatsoever. If jdln wants to use jQuery, let's assume he has good reason to do so. – Luke Jun 30 '15 at 05:00
  • There's loads of uses for this where media queries don't work, e.g. to activate a masonry effect only if screen width is larger than, say, 1000 pixels. – Pekka Dec 02 '17 at 20:31

12 Answers12

520

Use jQuery to get the width of the window.

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}
aziz punjani
  • 25,586
  • 9
  • 47
  • 56
  • 11
    Note that $(window).width() is not consistent across browsers if the scrollbar is visible. I've found that using [javascript media queries](https://github.com/eddiemachado/bones/issues/468#issuecomment-23626238) is much more reliable. – forsvunnet Dec 30 '13 at 12:36
  • 9
    @forsvunnet That link is dead. – Shah Abaz Khan Jun 07 '18 at 11:19
  • 2
    A link to javascript media queries: https://www.w3schools.com/howto/howto_js_media_queries.asp – Timar Ivo Batis Dec 07 '18 at 14:03
152

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.

jk.
  • 14,365
  • 4
  • 43
  • 58
  • 2
    Wrapping in the resize event only makes it fire on resize, not on load. – Ted May 22 '12 at 23:41
  • 7
    @Ted That's why I said `combine it with`. – jk. May 24 '12 at 18:52
  • Hey, would you mind explaining how I would go about combining this resize event? I have a function that I would only like to be loaded if the browser is greater than 960px in width, whether it was the window size on initial page load or before / after resizing. If I just add this snippet after my first window width detection, the function will have already loaded if the user starts at a browser width greater than 960px and then resizes down. Would it maybe be possible to clear an already fired function if the browser is resized to a width below 960px? – R.J. Sep 02 '12 at 06:45
  • 1
    @R.J. see edits above. I don't know what you mean by 'clear' an event so I went with preventing event from firing again. – jk. Sep 02 '12 at 14:42
  • 1
    Fantastic, I've been trying to figure out for days how to bind an `equalHeights` function on resize but for only widths greater than 768. This works like a charm. Thanks – Danny Englander Mar 13 '13 at 19:35
  • 1
    It makes sense to add a resize event after that code, so that on load whatever the current size of the browser is it will then run the needed code – BennKingy Sep 20 '19 at 11:27
83

I recommend not to use jQuery for such thing and proceed with window.innerWidth:

if (window.innerWidth < 960) {
    doSomething();
}
Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
19

You can also use a media query with javascript.

const mq = window.matchMedia( "(min-width: 960px)" );

if (mq.matches) {
       alert("window width >= 960px");
} else {
     alert("window width < 960px");
}
13
// Adds and removes body class depending on screen width.
function screenClass() {
    if($(window).innerWidth() > 960) {
        $('body').addClass('big-screen').removeClass('small-screen');
    } else {
        $('body').addClass('small-screen').removeClass('big-screen');
    }
}

// Fire.
screenClass();

// And recheck when window gets resized.
$(window).bind('resize',function(){
    screenClass();
});
leymannx
  • 5,138
  • 5
  • 45
  • 48
12

I would suggest (jQuery needed) :

/*
 * windowSize
 * call this function to get windowSize any time
 */
function windowSize() {
  windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
  windowWidth = window.innerWidth ? window.innerWidth : $(window).width();

}

//Init Function of init it wherever you like...
windowSize();

// For example, get window size on window resize
$(window).resize(function() {
  windowSize();
  console.log('width is :', windowWidth, 'Height is :', windowHeight);
  if (windowWidth < 768) {
    console.log('width is under 768px !');
  }
});

Added in CodePen : http://codepen.io/moabi/pen/QNRqpY?editors=0011

Then you can get easily window's width with the var : windowWidth and Height with : windowHeight

otherwise, get a js library : http://wicky.nillia.ms/enquire.js/

moabi
  • 1,381
  • 1
  • 9
  • 9
10

I know i'm late to answer this, but i hope it is of some help to anybody who have similar problem. It also works when page refreshes for any reason.

$(document).ready(function(){

if ($(window).width() < 960 && $(window).load()) {
        $("#up").hide();
    }

    if($(window).load()){
        if ($(window).width() < 960) {
        $("#up").hide();
        }
    }

$(window).resize(function() {
    if ($(window).width() < 960 && $(window).load()) {
        $("#up").hide();
    }
    else{
        $("#up").show();
    }

    if($(window).load()){
        if ($(window).width() < 960) {
        $("#up").hide();
        }
    }
    else{
        $("#up").show();
    }

});});
9

use

$(window).width()

or

$(document).width()

or

$('body').width()
Guard
  • 6,816
  • 4
  • 38
  • 58
3

My solution for the question using Vanilla JS is,

window.addEventListener("load", function () {
  if (window.innerWidth < 960) { doSomething(); }
}

This works, but with one problem, whenever resizing the screen in dev tools, which is a common thing for developers, the function does something will not be fired.

For example, if we display the webpage on a computer with a screen size of more than 1000px, the function will not be fired, and when we resize the windows to less than the target(here 960px) we expect the event to be fired but that is not what happens.

By the time the script file is already processed and finished and will not be re-read, so we need to fire an event whenever we resize the screen and handle that event using "addEventListener", Just like this;

window.addEventListener("resize", (e) => {
  const windowWidth = window.innerWidth;
  if (windowWidth > 960) { doSomething(); }
  if (windowWidth < 960) { doSomething(); }
});

The best practise is to combine both the code-snippets in the project.

M NARESH
  • 142
  • 1
  • 7
2

Try this code

if ($(window).width() < 960) {
 alert('width is less than 960px');
}
else {
 alert('More than 960');
}

   if ($(window).width() < 960) {
     alert('width is less than 960px');
    }
    else {
     alert('More than 960');
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JIBIN BJ
  • 105
  • 15
0

Simple and clean solution using Vanilla JavaScript

let app = document.getElementById('app')
 

const changeColorFn = ( app, color ) => {
  app.setAttribute("style",`background: ${color}`)
}


const winSizeFn = ( winWidth, callback, app, color ) => { 
  if (window.innerWidth < winWidth ) {
    callback(app, color);
  }
}


  winSizeFn( '1200', changeColorFn, app, 'red' )
  winSizeFn( '800', changeColorFn, app, 'green' )
  winSizeFn( '500', changeColorFn, app, 'blue' )


window.addEventListener("resize", (e) => {
  // add winSizeFn here if you want call function on window resize 
})
<div id="app">My app content</div>
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
-7

nope, none of this will work. What you need is this!!!

Try this:

if (screen.width <= 960) {
  alert('Less than 960');
} else if (screen.width >960) {
  alert('More than 960');
}
ChainFuse
  • 797
  • 2
  • 10
  • 26
  • 3
    Posting a link is not an answer. – nedaRM Sep 18 '13 at 05:53
  • sorry about that i was kinda in a hurry! Wait a minute, I'm doing it right now... – Saurav Chaudhary Oct 25 '13 at 14:35
  • please note if screen.width (best captured with `document.body.clientWidth` if using vanilla JS) is <= 960 (meaning the if statement here) then the only other option (ELSE is screen.width >960) therefore using else if here is redundant. use `document.body.clientWidth <=960 ? handleSmallerThan960() : handleLargerThan960()` or some variant. NO need for else if(redundant code) – Zargold Apr 11 '18 at 19:12