简体   繁体   中英

Fade in div once user scrolls past element

Problem:

I'm trying to fadeIn and fadeOut div class="audioBox" once the user scrolls past the header. What I have seems to work fine, except for when the page is loaded and I'm already past the 835px height of the header/

Q: What I'm seeing is when I scroll the audioBox quickly fades in and then fades out, despite scroll >= header How do I prevent this from happening?

scripts.js

// If the reader scrolls past header, show audioBox
var scroll = $(window).scrollTop();
var header = $("header").height();

if (scroll >= header) {
    $(".audioBox").fadeIn();
} else if (scroll <= header) {
    $(".audioBox").fadeOut();
}

I tried implementing what you're describing in jsfiddle at http://jsfiddle.net/3wqfp2ch/1/ .

I'd approach it a bit differently, based on the following ideas:

  • I personally prefer letting CSS take care of visual stuff via classes, and let jQuery take the simple responsibility of controlling when the classes should be added/removed. I think it makes for a better relationship between the two systems and allows each to do their thing better & more neatly.
  • I didn't see where you were listening for scroll events on the window, which is essential for figuring out whether a user's scroll position is before or after the header, so have included this in my code
  • I don't think we need multiple if conditions - there's just one question: "Is the scroll position greater than the header height?".

Here's the JS:

var headerHeight = $("header").height();
var audioBox = $('#audioBox');

$(window).on('scroll', function(){
  var scrollPosition = $(window).scrollTop();

  if (scrollPosition > headerHeight) {
    audioBox.addClass('is-visible');
  } else {
    audioBox.removeClass('is-visible');
  }
});

Check out my fiddle at http://jsfiddle.net/3wqfp2ch/1/ for the HTML & CSS that this relates to, and the working demo putting it all together.

I can't test whether this suffers from the same issue regarding you loading at a point already past the header height from jsfiddle unfortunately, but I wouldn't be expecting the behaviour you described using the code above.

Let me know how you get on!

Calling .fadeIn() or .fadeOut() all the time and having an overlap in the conditions might be the problem.

Try this:

// If the reader scrolls past header, show audioBox
var scroll = $(window).scrollTop();
var header = $("header").offset().top + $("header").height(); // should include the header's offset as well

if (scroll >= header) {
    $(".audioBox:hidden").fadeIn();
} else if (scroll < header) {
    $(".audioBox:visible").fadeOut();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM