0

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>

Jordyn H
  • 1
  • 2
  • You are not closing all your divs ... besides, nothing is flickering on Mac/Safari. The problem is probably buried in some elements/css underneath the `#fadeblock`. – Ole Sauffaus Jul 24 '15 at 06:36
  • On top of that, I'm wondering about your large padding (450+20px), inside an element of just 200x200px ... – Ole Sauffaus Jul 24 '15 at 06:39
  • Maybe you should verify if the element is visible before using fadeIn() - you don't need to fadeIn if it's already there (i.e. scroll >520). – verjas Jul 24 '15 at 06:40

1 Answers1

2

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?

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • I tried your script (with the .on and without the preventDefault, both were recommendations from other articles trying to remedy this) and I found no change in the flicker. I'll be the first to admit that as a major beginner I'm awful at jquery, so I'll try to figure this out! – Jordyn H Jul 24 '15 at 10:49
  • There is also no reason to use `.on()` unless you have injected content into the DOM after the page was initially rendered. Just use `$(window).scroll(function(){ // all stuff in here});` – cssyphus Jul 24 '15 at 14:42