Reputation: 149
I'm using the following code to show a div when it is scrolled into view. I would like to simplify this and show the div when the page loads and not when scrolled into view. Any help would be great. Many thanks.
var animateHTML = function () {
var elems,
windowHeight
var init = function () {
elems = document.getElementsByClassName('hidden')
windowHeight = window.innerHeight
_addEventHandlers()
}
var _addEventHandlers = function () {
window.addEventListener('scroll', _checkPosition)
window.addEventListener('resize', init)
}
var _checkPosition = function () {
for (var i = 0; i < elems.length; i++) {
var posFromTop = elems[i].getBoundingClientRect().top
if (posFromTop - windowHeight <= 0) {
elems[i].className = elems[i].className.replace('hidden', 'fade-in-element')
}
}
}
return {
init: init
}
}
animateHTML().init()
Upvotes: 0
Views: 219
Reputation: 191976
You can use Element#scrollIntoView to make the element visible in the viewport.
You can use the DOMContentLoaded event to know when the DOM is ready.
Note: the options object - { behavior: 'smooth', block: 'center' }
is only supported by Chrome and Firefox. Other browsers support only a the alignToTop
boolean, and since the object will evaluate to true
the element will jump to the top.
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector('.active').scrollIntoView({
behavior: 'smooth',
block: 'center'
});
});
.block {
width: 100px;
height: 100px;
border: 1px solid red;
}
.active {
border: 1px solid blue;
}
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block active">Scroll into view</div>
<div class="block"></div>
<div class="block"></div>
Upvotes: 1