I am trying to change the name of a class tag dynamically when a user loads the page based off of the screen size. Here is the code:
<!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>
However, the page is thrown into an infinite loop and cannot load the data. Is there an easy way to set the class named based on the size of the screen? Can I use an "if conditional" check when the page loads? I have also included a JSFiddle. I don't know how much that will help however.