1

I am having issues with a js script on a menu. I have the same menu but styled differently for pc and smaller versions. And I want this script to only affect the menu when the screen is lower than x width. How can I achieve this? This is my script

    var dropdown = document.getElementsByClassName("dropdown-btn");
    var i;

    for (i = 0; i < dropdown.length; i++) {
      dropdown[i].addEventListener("click", function() {
      var dropdownContent = this.nextElementSibling;
      if (dropdownContent.style.display === "block") {
      dropdownContent.style.display = "none";
      } else {
      dropdownContent.style.display = "block";
      }
      });
    }

    }
clauu
  • 91
  • 6

3 Answers3

2

Check the width of the window (cross-browser) then conditionally run your script.

var x = 400,
w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (w < x) {
  console.log(w, 'true')
  // do stuff here when screen is smaller
} else {
  console.log(w, 'false')
  // do stuff here when screen is larger
}
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31
  • More info here https://stackoverflow.com/questions/1766861/find-the-exact-height-and-width-of-the-viewport-in-a-cross-browser-way-no-proto – Arleigh Hix Apr 23 '19 at 17:45
1

You can use window width property of JQuery

if ($(window).width() < x)
{
    //Code here
}
Sailesh Babu Doppalapudi
  • 1,534
  • 1
  • 10
  • 22
1

To check the width of window (cross-browser), you may use window, screen and width property of JavaScript.

It might help you :

//Smaller screen sizes
var size = 768; 
if(window.screen.width < size) {
    //Your code for smaller screen sizes here
}
else
{
    //Your code for Larger screen sizes here
}
Kamran Allana
  • 543
  • 1
  • 6
  • 25