Jeppa Jeppa - 1 month ago 7
Javascript Question

Disable jquery script if width is below 480



function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 0,
header = document.querySelector("header");
if (distanceY > shrinkOn) {
classie.add(header,"smaller");
} else {
if (classie.has(header,"smaller")) {
classie.remove(header,"smaller");
}
}
});
}
window.onload = init();

body {margin-bottom:2000px;}
header {
height:80px;
position:fixed;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-ms-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
background:grey;
width:100%;
}

header.smaller {
height:30px;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-ms-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
}

<script src="http://callmenick.com/_development/resize-header-on-scroll/js/classie.js"></script>

<body>
<header>
header
</header>
</body>





Hello im using a jquery shinking header plugin and it works perfect. Just dont want to use this effect on browsers below an width of 480px. Is there a way to disable the plugin on browsers below 480px?

Help would be highly appreciated,
Best regards!

Answer

UPDATED.

Since you are not using jQuery, check the code below with plain Javascript.


Replace your code with the code below:

window.onresize = function() {

  if(window.innerWidth > 480) { 

  // your code will only run if width of window is over 480px

    // === START OF YOUR CODE ===

    window.addEventListener('scroll', function(e){
        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
            shrinkOn = 0,
            header = document.querySelector("header");
        if (distanceY > shrinkOn) {
            classie.add(header,"smaller");
        } else {
            if (classie.has(header,"smaller")) {
                classie.remove(header,"smaller");
            }
        }
    });

    // === END OF YOUR CODE ===
  }
};

window.dispatchEvent(new Event('resize'));
// triggers resize event so user doesn't have to only resize to trigger your code