Go Back

Running Javascript on Specific Screen Widths

There may be certain times when you want to perform Javascript functions only at particular view levels.  For instance, let’s say you have a Javascript animation intended to run on desktop on an SVG within your site, but choose to omit running the animation on mobile.  Maybe it’s resource intensive or whatever.  In fact, you don’t want the SVG to appear at all on mobile.

How do you tell the script to only run on the desktop display?  The first instinct would be to do the following

if (window.innerWidth() > 768 ){
     doDesktopOnlyFunctions();
}

However, this method sucks! The reason is that it requires use of the window object.  The window object varies in performance depending on what browser you are using.  The window.innerWidth() method also includes stuff like scroll bars and other things that CSS do not consider to be part of the width.  I’m sure a superstar techie can tell you exactly why, but anecdotally I’ve never seen screen widths from the window object exactly match up to what CSS considers the width.  So, the Javascript may run when not intended or vice versa.

The following method is much better and more consistent because it runs Javascript based on what CSS sees as the media’s width.  Basically, the SVG in question is told by the CSS media query to hide itself on tablet view or below.  The JQuery then asks if the SVG is “visible” or not, and only runs if the SVG is not hidden.  So, the visibility is determined by the CSS itself. This method is great, consistent, and my go-to for running Javascript on specific screen widths.

HTML
<head>
    <title>Show/Animate the SVG only on Desktop</title>
</head>
<body>
    <svg id="animation-wrapper">
    </svg>
</body>
CSS
#animation-wrapper {
    display: block;
}
@media (max-width: 768px){
    #animation-wrapper {
        display: none;
    }
}
Javascript
if($("#animation-wrapper").is(":visible")){
    doDesktopOnlyFunctions();
}

Important Note:  What JQuery considers visible are elements that have a display setting of display: block, display: inline-block, or display: inline. I have read; however, that display: inline will sometimes return false when using the jQuery.is(“:visible”) method. So, using display settings of display: block or display: inline-block will have the most consistent results for returning true. Also, though jQuery uses the attribute visible in its method, this is not equal to the CSS attribute of visibility. So visibility: hidden in your CSS will return true using the jQuery method above.