Hide an element with jQuery whilst scrolling

It's rude to point
It's rude to point

Today I came across an interesting problem that no amount of Google searches could solve. So I had to knuckle down and come up with a solution - and surprisingly it was much more simple that it had first appeared.

So the problem is hiding an element when a user is scrolling - it might be a menu, a header, or a picture of my cat, Sophie. Either way we can't just use the simple delay() function in jQuery to help us out - we need to use some raw JavaScript. To accomplish this we will create a variable into which we will place the current scroll amount of the page, we will then wait for a period of time, and check if that scroll amount has changed. If it has we will leave the element hidden, otherwise we'll show it to the user again.

And here's the rather simple code to do just that:

$(document).scroll(function(){
	$('section').fadeOut();

	var scrollA = $('body').scrollTop();

	setTimeout(function(){
		if(scrollA == $('body').scrollTop()){
			$('section').fadeIn();
		}
	}, 200);
});

And there we have it! A really simple effect made easy with a tiny bit of JavaScript.

You can check out the fiddle over here: http://jsfiddle.net/LJVMH/

***

If you found this particularly useful and want to share the ♥ you can donate here.

***

2 Responses

  1. Tray

    i like your coding..and i'm thinking of using it in my website...but i want to disable this after i call another function in my javascript..how do i disable this?..can you help me.

    Reply
    • Tom

      You would simply use: $(document).unbind('scroll'); in your function.

      Reply

~ Add a response ~

Please ensure you have filled in all fields with appropriate information!