I have to show/hide the image based on scrolling. But the condition here is, if the user scrolls up and down many times near the page top/bottom, the image should not fade in and fade out repetitively. It should listen for 1 sec before fade in. Below is the logic that i tried.
Code
<div class="a" style="height: 300px;width: 300px;background-color: green;position:fixed;">
</div>
var $toTop = $('div.a');
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$toTop.fadeIn();
} else if ($toTop.is(':visible')) {
$toTop.fadeOut();
}
});
You can do this by saving a timeout in jquery main data object that waits for a second to execute whenever scroll event is fired. The event also clears any previously registered timeouts:
var $toTop = $('div.a'); $(window).scroll(function() { clearTimeout($.data(this, 'waitASecond')); $toTop.stop(); $.data(this, 'waitASecond', setTimeout(function() { if ($(window).scrollTop() > 100) { $toTop.fadeIn(); } else if ($toTop.is(':visible')) { $toTop.fadeOut(); } }, 1000)); });
body { height:1000px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> Scroll Down and wait.... <div class="a" style="height: 700px;width: 300px;background-color: green;display:none"></div> </body>
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.