Make something appear/disappear as it approaches top of window

Long story short, I have a slider with a next/prev on the edge of the window in the vertical center of a page. For visual element clipping reasons, I’d like to make the item disappear when the element is X pixels (or less) from the top of the window when users start to scroll down.

I’m guessing I would need to bind something to the scroll of the body to check the distance, and if too low, fade the elements out.

A good way to achieve that is to set up a timer that checks the distance on a regular basis, such as on a 500ms basis.

Is that considered a safe amount of time that wouldn’t burden most browsers/computer setups?

Yes, half a second is plenty of time to not burdon a browser. They can even handle 50ms, but for the task that you have in mind, 500ms (half a second) is plenty enough. Feel free to increase it though to whatever you feel comfortable with. By experimenting with different delay speeds, you can check on how that will affect things with the effect that you want to apply.

Hi aaron.martone,

My opinion would be to bind event on scroll, something like :

$(window).bind(“scroll”, function(){
//your code
});

before that unbind the event : $(window).unbind(“scroll”);

Using the onscroll event would result in extreme performance problems, because that function will be called every single time that the page scrolls. It’s been known to grind IE to a halt, for example.

Really?
So are you saying that it’s computationally less expensive to fire a function that checks an element’s position (where a reference to the element is cached) every 500ms, than to attach an onscroll event handler to the main window?

It would be interesting to see a performance comparison of the different techniques when something is being faded in and out, perhaps with http://jsperf.com/

I agree.

The reason I ask this, is because I had to do something similar recently and wasn’t sure of the right way to go.
I contemplated both techniques and ended up using onscroll.

What worries me about using onscroll, is in regard to the fading technique that is going to be firing its own set of timers to perform the fade. That seems to be a recipe for things becoming quite messy when scrolling.

Also, whenever you are scrolling, the event onscrolling event is triggering as fast as it can on the computer, which can be every 20 milliseconds. (50 times a second).
Contrasting that with checking every 500 ms (twice a second) seems to be preferable in a situation that doesn’t require precise timing, but I could be wrong.

It would be interesting to have a test page of what the OP is intending to fade, so that different techniques could be explored and experimented with.

I deal with that simply by comparing the time between calls. If the difference is too small, don’t execute the handler’s code.

Sure would.

@aaron_martone ;
Any chance you could provide us with a link to the page with the slider?