I'm attempting to dynamically change the class tag's name when a user visits the page based on the screen size. Below is the code snippet I've used:
<!DOCTYPE html>
<html>
<body onload="changeClass()">
<section class="example">
<p>Hello</p>
</section>
<section class="example">
<p>New section</p>
</section>
<script>
function changeClass() {
var x = document.getElementsByClassName('example');
var width = (window.innerHeight > 0) ? window.innerHeight : screen.Height;
console.log(width);
if(width <= 640) {
while(x.length > 0) {
x[1].className ='newClass';
}
} else {
while(x.length > 0) {
x[0].className = "example";
}
}
}
</script>
</body>
</html>
Unfortunately, the page enters an infinite loop and fails to load the data. Is there a simple way to set the class name based on the screen size? Can I use an "if conditional" statement when the page loads? I've included a link to a JSFiddle, but I'm unsure how much that will assist in resolving the issue.