Search code examples
javascriptmedia-queriesaddeventlistener

Execute javascript code ONLY if width is higher than x pixels


I'm trying to execute a javascript function ONLY if the width is bigger than 1200pixels.

The code I need to execute works, but the check for the screen size doesn't:

window.addEventListener("resize", function(){
    if (document.documentElement.clientWidth > 1203) {
            <<<some other code that's working>>>
    }
}, true);

All this code is in a javascript file outside the document.ready function.

EDIT: When you drag your screen window around, it isn't working like normal css queries. This is the problem. It works if you refresh your page, but if you change the width of your browser, then it doesn't adjust, it needs the reload right now.

That's my issue.


Solution

  • You need to add an else clause to get the behaviour you want. Otherwise the resize event will only work going one way, as you described.

    window.addEventListener("resize", function(){
        // fire when above 1203
        if (document.documentElement.clientWidth > 1203) {
          console.log('Greater!');
        }
        // fire when below 1203
        else {
          console.log('Smaller!');
        }
    }, true);
    

    Here's a link to the fixed jsfiddle that planet260 wrote: http://jsfiddle.net/4dnemh2j/4/

    Here's my example again: https://jsfiddle.net/9n5hmpua