ulbby
ulbby

Reputation: 43

jQuery: How to detect when user scrolls to the top again?

On the top of my site I have a bar with similar blog posts. **It should SlideUp (with jQuery) when the user have scrolled to the top again - so e.g. after he read the article.

How can I detect this situation and then show the bar in the head of my site?**

Upvotes: 3

Views: 3868

Answers (2)

mohsen dorparasti
mohsen dorparasti

Reputation: 8415

you can monitor scroll event of window element,and check its scrollTop() :

$(window).scroll(function () {
    if ($(this).scrollTop()  <= 0 ){
        // your code
    }
});

Upvotes: 9

Robin
Robin

Reputation: 21894

It's easy to check the scroll position with .scrollTop() in jquery.

So the idea is to bind an event on scroll to check the position periodically.

hasReadArticle = false
$window = $(window)
articleBottomPosition = ... # get the position of the bottom of the article 
timeout = nil

$window.on "scroll", (e) ->
   clearTimeout timeout if timeout

   timeout = setTimeout ->
     top = $window.scrollTop()

     # you might want to improve this to detect when the bottom of your window arrives at the bottom of the article.
     hasReadArticle = top > articleBottomPosition unless hasReadArticle

     if top <= 0 && hasReadArticle
       # $('your header').slideDown()
   , 100

A simpler way to do it would be to use jquery-waypoints. You would set a handler to detect when you get to the bottom of your article, then set a variable to remember this. Then set another handler to detect when you get to the top of the page (with direction == "up").

Upvotes: 0

Related Questions