Reputation: 2887
I know how to run code when user scrolls to a specific point, but I can't find questions about showing an element while user scrolls (no matter where or to where) then hiding it when user stop scrolling. Is there a straightforward way to achieve this in jQuery?
Upvotes: 0
Views: 1917
Reputation: 35670
Use fixed positioning on your element, and use this event:
$(window).scroll(function() {
$(element).stop(true, true).show().fadeOut('fast');
});
This will show the element while scrolling then fade it out when scrolling has stopped. The stop()
method stops the currently-running animation.
Upvotes: 2
Reputation: 587
jQuery dont have event "scrollStop" so you can use a setTimeout to do your action
<div>
<div class="fade">
Scroll down i will become invisible
</div>
</div>
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
$('.fade').show();
$.data(this, 'scrollTimer', setTimeout(function() {
// do something
$('.fade').hide();
}, 250));
});
http://jsfiddle.net/onqn2gjj/896/
Upvotes: 1
Reputation: 2576
My suggestion is to use one function to show the element when scrolling is done immediately, and then hiding it a certain amount of time afterward. If we scroll again, we instead basically "push" the timer a little further back. This is basically the concept of debouncing, which you may have heard of. Therefore, my solution looks like this:
var hideTimeout = null;
var show = function() {
$('#theone').show();
}
var hide = function() {
$('#theone').hide();
}
$(document).ready(function(){
$(window).scroll(function(e){
if (hideTimeout) {
window.clearTimeout(hideTimeout);
hideTimeout = null;
}
show();
window.setTimeout(hide, 500);
});
});
https://jsfiddle.net/386bstgh/1/
Upvotes: 1