简体   繁体   中英

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');
}

Use jQuery to get the width of the window.

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

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 RJ:

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.

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

if (window.innerWidth < 960) {
    doSomething();
}

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");
}
// 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();
});

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/

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();
    }

});});

use

$(window).width()

or

$(document).width()

or

$('body').width()

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>

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.

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>

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM