Atomix
Atomix

Reputation: 125

Can't get this statement to work

I would like my element to show with position fixed only when offset().top is bigger than 300px

Here is my code:

$(window).scroll(function() {   
    if ($(window).offset().top > 300) {
        $(".uparrow").css('position','fixed');
    }
    else {
        if ( $(window).offset().top < 300) {
            $(".uparrow").css('display','none');
        }
    }
})

Upvotes: 0

Views: 42

Answers (1)

Darren Wainwright
Darren Wainwright

Reputation: 30727

Your browser console is your friend. This will tell you right away what is wrong. In this case you would have received an error in your console Uncaught TypeError: Cannot read property 'top' of undefined - this would lead you down the path to fixing your issue.

You need $(window).scrollTop() not $(window).offset().top

You also do not need your second if statement. This is covered by your previous else statement

I.E

$(window).scroll(function()
   {   
     if ( $(window).scrollTop() >= 300)    
     {
         $(".uparrow").css('display','inline-block');
         $(".uparrow").css('position','fixed'); // <- this is pretty pointless given you never change it when less than 300 pixels.
         console.log('I am fixed');
     }
     else 
     {
       $(".uparrow").css('display','none');
       console.log('I am hidden');
     }
  })

Upvotes: 2

Related Questions