Hide an element when a certain amount of scrolling has occured

36,581

Solution 1

It seems to work fine here: http://jsfiddle.net/maniator/yDVXY/

$(window).scroll(function() {
    if ($(this).scrollTop() > 200) { //use `this`, not `document`
        $('.fixedelement').css({
            'display': 'none'
        });
    }
});

Solution 2

Try this.

$(window).scroll(function(){
  if($(document).scrollTop() > 200){//Here 200 may be not be exactly 200px
    $('.fixedelement').hide();
  }
});
Share:
36,581
Fuego DeBassi
Author by

Fuego DeBassi

Updated on January 19, 2020

Comments

  • Fuego DeBassi
    Fuego DeBassi over 4 years

    I'd just like to hide an element on my page, after N number of pixels have been scrolled.

    $(window).scroll(function(){
      if($(document).scrollTop() > 200){
        $('.fixedelement').css({'display': 'none'});
      }
    });
    

    I thought this might work, and after 200px of scrolling the .fixedelement would vanish. Alas, it doesn't work. Any thoughts?

    • Naftali
      Naftali almost 13 years
      what does your html look like?
    • Joseph Marikle
      Joseph Marikle almost 13 years
      tested and it works for me... There appears to be nothing wrong with the code.
  • Phil
    Phil almost 13 years
    this makes no difference, hide() == { display: 'none' }
  • Naftali
    Naftali almost 13 years
    @Shankar -- that is true. I am just showing that the code does work that the OP has in the question
  • ShankarSangoli
    ShankarSangoli almost 13 years
    Yes, I think the acutal problem to the user is with 200px. 200 scrolltop may not be equal to 200px.
  • Naftali
    Naftali almost 13 years
    @Shankar -- it uses integers not a string. if you output $(this).scrollTop() on every scroll you would see that.
  • Fuego DeBassi
    Fuego DeBassi almost 13 years
    You're right. I got this working. Next problem. What if I don't want to hide after a certain amount of scrolling, what if I want to hide at a specific page position. Say, 900px from the top of the viewport, once that point is scrolled PAST... it hides. This way my action isn't entirely dependent on the height of the viewport.
  • ShankarSangoli
    ShankarSangoli almost 13 years
    @Neal - I know it returns an integer.
  • Billu
    Billu over 6 years
    @Neal, nice script