April 15, 2012

CSS JS Display none alter div

Question by Michael

I have a one pager. And in that one pager, I have an item that is set as display:none (fixed side nav in a div).

Can I have it show when scrolling to a certain div?

So it starts out in the code but not displayed, and then when the user scrolls to #about can the side nav show up?

Answer by Parker

Essentially you will need to check if the user has scrolled to or beyond the div id of about.
First you will need to establish the current Y value of the div.

//cache about div
var about = $('#about');
//this caches the about div position on window load
var aboutPosition = about.position();

Next you will need to determine how far the the user has scrolled. The best way I have determined to accomplish this is with a timer. You could use the scoll event but its far too taxing on the user browser and a timer will be for the most part indistinguishable.

//generic timer set to repeat every 10 mili(very fast) 
//with a callback to execute the logic
var checkScrollPos = window.setInterval("scrollTopLogic()",10);

function scrollTopLogic(){
    //if about y position is greater than or equal to the 
    //current window scroll position do something
    if(aboutPosition.y >= $(window).scrollTop()){
        $('nav').show();
        //remove timer since it is no longer needed
        window.clearInterval(checkScrollPos);
    }
}

Answer by Starx

You can catch the scroll event of the div and show the element like this

$("#div").scroll(function() {
   $("#item").show();
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!