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()
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.