In the code below, I want the page to go from "hello 1" to "hello 5" when the page loads then it have to swipe up -100vh. It runs well but it shows an error in console in inspect element. Can anyone tell me where am I making mistake?
Following are the error in the console page-
Uncaught TypeError: Cannot read properties of undefined (reading 'style').
I am using the "break;" to end the task but it shows an error for "break;".
Snippet
window.addEventListener('load', function() {
var texts = document.getElementsByClassName('loading-text');
var roll = document.getElementById('loading-page');
var lta = document.getElementById('last_text');
var i = 0;
var interval = setInterval(function() {
texts[i].style.opacity = '0';
i++;
if (i === texts.length) {
clearInterval(interval);
lta.className = "last_text_active";
roll.style.top = '-100vh';
// break;
}
texts[i].style.opacity = '1';
}, 1000);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.on-load-page-container {
width: 100%;
height: 100vh;
color: #fff;
}
.on-load-page-container #loading-page {
background-color: #000;
display: flex;
align-items: center;
justify-content: center;
top: 0;
width: 100%;
height: 100%;
pointer-events: none;
position: relative;
transition: all 1s ease-in-out;
}
#loading-texts {
position: fixed;
text-align: center;
font-size: 24px;
font-weight: bold;
color: #fff;
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.loading-text {
/* display: none; */
opacity: 0;
position: absolute;
}
.last_text_active {
opacity: 0;
}
<div class="on-load-page-container">
<div id="loading-page">
<div id="loading-texts">
<p class="loading-text" style="opacity:1;">hello 1</p>
<p class="loading-text">hello 2</p>
<p class="loading-text">hello 3</p>
<p class="loading-text">hello 4</p>
<p id="last_text" class="loading-text">hello 5</p>
</div>
</div>
</div>
3
Answers
break
is used to end a loop or switch, not a function.Replace
break
withreturn
to skip the last line:You are getting error in console as it is receiving the
undefined
value oftexts[i]
at the last indexYou can add a condition weather the value is not undefined then only change the opacity like this,
So your JS code will be as follows,
Hmm… Here you’re stopping the loop when
i
equals the number of elements intexts
, but the index won’t reach that because JS begins indexes from0
.I think you should stop the loop when
i
equalstexts.length - 1
instead:Hope it works 🙂