Search code examples
javascripthtmlcssmedia-queries

Is it possible to only trigger a media query if a certain variable is a certain value?


I am trying to remove an element from my window if the screen size is below a 1000px and variable is greater than 15.

I have my css file:

@media (max-width: 1000px){
  #specific-id{
     display:none
   }
}

but I only want this to occur if the variable is greater than 15. How can I implement javascript control to this?


Solution

  • I think the best way for this is to add a class that is only added if variable is bigger than 15:

    if variable is less than 15:

    const variable = 0
    const specificId = document.getElementById('specific-id')
    
    if (variable > 15) {
      specificId.classList.add("variableIsMoreThan15")
    }
    #specific-id {
      background: red;
    }
    
    @media (max-width: 1000px){
      .variableIsMoreThan15 {
         display:none
       }
    }
    <div id="specific-id">
    Hello
    </div>

    if variable is greater than 15:

    const variable = 16
    const specificId = document.getElementById('specific-id')
    
    if (variable > 15) {
      specificId.classList.add("variableIsMoreThan15")
    }
    #specific-id {
      background: red;
    }
    
    @media (max-width: 1000px){
      .variableIsMoreThan15 {
         display:none
       }
    }
    <div id="specific-id">
    Hello
    </div>