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?
CodePudding user response:
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>
CodePudding user response:
I think you can use a custom media query you can try
Here is an example of implementation in the documentation:
Define a map of names to values for JS. Values can be either a MediaQueryList object or a boolean, in which case it’s treated identically to the above, or can be a number or a string, in which case it’s treated like a normal MQ, and can use the normal or range context syntax. Like:
<script>
CSS.customMedia.set('--foo', 5);
</script>
<style>
@media (_foo: 5) { ... }
@media (_foo < 10) { ... }
</style>
Documentation Link: https://www.w3.org/TR/mediaqueries-5/#custom-mq