I've built a small script to let chosen objects fade in when the user scrolls down. My problem is that this script is pretty static. If I applied this on 20 different objects, say, I would have to set the height every time. Here is an example:
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 500) {
$(".header-js-scroll-fade").css({"opacity" : "1"});
$(".home-vorteile").addClass("header-img-fade-in-by-scroll");
}
else {
$(".header-js-scroll-fade").css({"opacity" : "0"});
$(".home-vorteile").removeClass("header-img-fade-in-by-scroll");
}
});
});
.header-js-scroll-fade {
opacity: 0;
transition: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="vorteile-text">Vertrauen durch,</h1>
<section class="home-vorteile">
<div class="header-js-scroll-fade header-img-fade-in-by-scroll">
<img src="https://via.placeholder.com/500" />
<h2>Sicherheit.</h2>
</div>
<div class="header-js-scroll-fade header-img-fade-in-by-scroll">
<img src="https://via.placeholder.com/500" />
<h2>Neueste KI Technik.</h2>
</div>
<div class="header-js-scroll-fade header-img-fade-in-by-scroll">
<img src="https://via.placeholder.com/500" />
<h2>Beste Materialien.</h2>
</div>
</section>
This checks if the element is visible by the user, if so it adds the class, if not it removes it. To make this happend you just need to apply the class header-js-scroll-fade
to any element you want.
The function isInViewport is from the User Tom Pažourek, found here: https://stackoverflow.com/a/40658647/8605830
// https://stackoverflow.com/a/40658647/8605830
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(document).ready(function () {
$(window).scroll(function () {
$('.header-js-scroll-fade').each(function () {
if ($(this).isInViewport()) {
$(this).addClass("visible");
}
else {
$(this).removeClass("visible");
}
});
});
});
.header-js-scroll-fade {
opacity: 0;
transition: 0.5s;
}
.header-js-scroll-fade.visible {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="vorteile-text">Vertrauen durch,</h1>
<section class="home-vorteile">
<div class="header-js-scroll-fade">
<img src="https://via.placeholder.com/500" />
<h2>Sicherheit.</h2>
</div>
<div class="header-js-scroll-fade">
<img src="https://via.placeholder.com/500" />
<h2>Neueste KI Technik.</h2>
</div>
<div class="header-js-scroll-fade">
<img src="https://via.placeholder.com/500" />
<h2>Beste Materialien.</h2>
</div>
</section>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加