clauu
clauu

Reputation: 91

JS script only for tablet/mobile

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

    }

Upvotes: 1

Views: 958

Answers (3)

Kamran Allana
Kamran Allana

Reputation: 946

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
}

Upvotes: 1

Arleigh Hix
Arleigh Hix

Reputation: 10877

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
}

Upvotes: 2

Sailesh Babu Doppalapudi
Sailesh Babu Doppalapudi

Reputation: 1544

You can use window width property of JQuery

if ($(window).width() < x)
{
    //Code here
}

Upvotes: 1

Related Questions