Reputation: 1
I have a div that is appearing on scroll after 520px. Every time I scroll down, it appears to fade in and then constantly flickers, like it keeps running the function over and over again. I've googled this endlessly and I can't find a fix that actually works. (It's on Chrome). Here's my Jquery:
$(window).bind("scroll", function(e) {
e.preventDefault();
if ($(this).stop().scrollTop() > 520) {
$("#fadeblock").fadeIn();
} else {
$("#fadeblock").stop().fadeOut();
}
});
And this is my CSS
#fadeblock {
display:none;
position:fixed;}
#sidebar {
width:200px;
height:200px;
padding:450px 20px 20px 20px;
position:absolute;
margin-left:3%;
}
HTML:
<div id="fadeblock">
<div id="sidebar">
<div id="title">{Title}</div>
<div id="desc">{Description}</div>
<div id="links">
<a href="/">link</a>
<a href="/">link</a>
<a href="/">link</a>
<a href="/">link</a>
</div>
Upvotes: 0
Views: 1866
Reputation: 40028
In fact, your code does keep running the function again and again.
One solution is to set a variable to keep track of the DIV's state:
var pos=0, fadedIn=false;
$(window).on("scroll", function(e) { //usually, just use: $(window).scroll(function(){
e.preventDefault(); //this line probably unnecessary
pos = $(this).scrollTop();
if (!fadedIn && pos > 520) {
$("#fadeblock").fadeIn();
fadedIn = true;
} else if (fadedIn) {
fadedIn = false;
$("#fadeblock").fadeOut();
}
});
Also:
1) If you are using a version of jQuery > 1.7, use .on()
instead of .bind()
2) Unless you have a good reason for doing so, do not use e.preventDefault()
on window.scroll()
See Also:
http://davidwalsh.name/javascript-debounce-function
How to implement debounce fn into jQuery keyup event?
Upvotes: 2