skip to Main Content

Below is some Javascript that I’m using for the mobile menu on my website. This Javascript stops content outside the menu from scrolling when the mobile menu is open and closes the menu when an item inside of it is clicked.

document.getElementById('cp_toggle03').onchange = function() {
 if (document.getElementById('cp_toggle03').checked) {
 document.body.style.overflow = "hidden";
  } else {
 document.body.style.overflow = "";
  }

}


var elements = document.getElementsByTagName('li');
var closeHamp = function() {
 document.getElementsByClassName('cp_menuicon')[0].click();
    };



for (var i = 0; i < elements.length; i++) {
 elements[i].addEventListener('click', closeHamp, false);
    }

Is there a way to set it so that this code only runs when on a specific screen size? I’ve tried using this Javascript to do so but haven’t had any luck getting it to run propperly.

function execute(){
   if(screen.width <= 768) {
   
     }

If anyone has any suggestions as how I could get this Javascript to work on a specific screen size I’d appreciate you letting me know.

My Website

2

Answers


  1. I think you are looking for document.body.clientWidth which represent the size of the body tag (borders are not included, but padding is). the screen variable you used represent the real screen width (e.g: 1920) therefore it will not change with the browser resize

    Login or Signup to reply.
  2. you can use a combination of JS and the window.matchMedia method. This method allows you to add a listener for changes in the screen size and conditionally execute the desired functionality.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search