Namanyayg Namanyayg - 26 days ago 13
CSS Question

Change Element Style On Page Scroll

I want to change the visibility of an element after the user scrolls down 100px.

I have some code already,

var fixed = false;
$(document).scroll(function() {
if( $(this).scrollTop() >= 100 ) {
if( !fixed ) {
fixed = true;
$('#logo-scroll').css({position:'fixed', display:'visible !important'});
}
} else {
if( fixed ) {
fixed = false;
$('#logo-scroll').css({display:'none'});
}
}
});‚Äč


JSFiddle.

The code has two problems.


  1. It doesn't default to be invisible, I want it so it starts invisible.

  2. It doesn't repeat, when the user scrolls back up, it doesn't go back being invisible.



More details,

I want to make something like this header, but, as you can see, there's a certain point where you see half of the small logo, and a PART of the bigger one. It doesn't affect techcrunch much as the header is small, but on my site, it does. I have made everything, I just need to start it in
display:none
, and become visible after 100px.

Answer

Use: display:block; and display:none;

jsFiddle DEMO

Add this to your CSS:

#logo-scroll{ display:none; position:fixed; }

jQ:

var $logo = $('#logo-scroll');
$(document).scroll(function() {
    $logo.css({display: $(this).scrollTop()>100 ? "block":"none"});
});

BTW: on TC page it's just a CSS play with z-indexes. nothing more. all elements are visible at page load, it's just the scroll that makes appear a z-index lower element beneath the big logo.

In plain Javascript would be like this:

var win = window,
    docEl = document.documentElement,
    $logo = document.getElementById('logo-scroll');

win.onscroll = function(){
   var sTop = (this.pageYOffset || docEl.scrollTop)  - (docEl.clientTop || 0);
   $logo.style.display =  sTop > 100 ? "block":"none" ;
};