简体   繁体   中英

How do I make a JavaScript function “off limits” based on the pixel width of the screen?

I have seen a lot of stuff on how to trigger a function right when the screen width goes past the defined max or min value but for my purpose I do not want the function to happen immediately. Here is a snippet of a JS function from W3 schools as an example.

function myFunction() {
  var x = document.getElementById("myLinks");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

Lets say I only wanted to have "access" to this function if my screen width is 500 or less and if it is 501 or more than it will not be using this function. In my circumstance there will be no other function for when it is above the specified width it will be doing something else by default. The JavaScript function that I need to happen would be is an onClick event that should only be able to happen if the screen is below the specified width.

You can simply wrap the contents of the function in an if that checks the width of the page's viewport against the value you want (eg, 500 ), or just immediately return out of the function, which saves a couple of curly braces.

function myFunction() {
  if (window.innerWidth > 500) return;
  var x = document.getElementById("myLinks");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

If you're trying to ensure the function isn't used incorrectly by other developers, you could instead throw an error, eg,

if (window.innerWidth > 500) throw new Error("This function should not be called on viewports smaller than 500px width!");

I'd stick to a @media rule here, and instead of setting style.display directly, add/remove a class.

JS:

function myFunction() {
  document.getElementById("myLinks").classList.toggle("mobile_hidden");
}

CSS:

@media screen and (max-width: 500px) {
  .mobile_hidden {
    display: none;
  }
}

An additional benefit of this is that resizing the window will auto-hide the element if it has the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM