I'm a newbie in coding. I knew this can be done by css, but want to do it by using JavaScript. I have a div tag and would like to not show it under 630px screen size. I searched this site and find this JavaScript code in another question and I liked it:
if( window.innerWidth > 630 ) {
//Your Code
}
But as I'm newbie I'm not familiar on how to insert it in my PHP code and where to insert div so it only works for screen above 630px.
Here is a way to hide a div when the width of the screen is smaller then 700px
function myFunction(x) {
if (x.matches) { // If media query matches
document.getElementById("divIWantedToHide").style.visibility = "hidden";
} else {
document.getElementById("divIWantedToHide").style.visibility = "visible";
}
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction)
<div id="divIWantedToHide">
tset
</div>
Personally I would recommend you to use CSS for this to be more precise media querys.
@media only screen and (max-width: 700px) {
#divIWantedToHide {
display: none;
}
}
<div id="divIWantedToHide">
tset
</div>
</div>
This is more of an event
issue:
At the basic level, this is how you could toggle by resize
event
:
var el = document.getElementById("yes"); //get the element node
//target resize event
window.onresize = function(){
//this will check everytime a resize happens
if(window.innerWidth > 630)
{
//if width is still bigger than 630, keep the element visible
el.style.display = "block";
//exit the funtion
return;
}
//At this point, the width is less than or equals to 630, so hide the element
el.style.display = "none";
}
<div id="yes">
Yey! I am visible
</div>
</div>