Change the background color of the title while scrolling the page

I was looking for a solution for this, but I can't get it to work.

I want the title of my page to change from a transparent background to a white background when the user starts scrolling the page.

HTML code:

<div class="header"> <div class="topbar"></div> <div class="sitelogo"></div> <nav id="navigation"> <ul> <li id="twitter"><a href="http://www.twitter.com/iamdanmorris"><em>Twitter</em></a></li> <li><a href="#contact">Contact</a></li> <li><a href="#blog">Blog</a></li> <li><a href="#">Portfolio</a></li> <li><a href="#">About</a></li> <li><a href="#">Home</a></li> </ul> </nav> <div style="clear:both;"></div> </div> 

CSS code:

 .header { position: fixed; top: 0; left: 0; width: 100%; padding: 0; z-index: 10000; -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25); -moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25); box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25); transition: all 0.2s ease-in-out; height: auto; background-color:transparent; } 
+5
source share
1 answer
 $(window).on("scroll", function() { if($(window).scrollTop() > 50) { $(".header").addClass("active"); } else { //remove the background property so it comes transparent again (defined in your css) $(".header").removeClass("active"); } }); 

script: http://jsfiddle.net/634d6vgq/2/

This will add the background-color: #fff element to the element if the user has scrolled more than 50 pixels from the top

This will add an β€œactive” class so you can style it in css (easier to maintain)

edit:

 $(function() { $(window).on("scroll", function() { if($(window).scrollTop() > 50) { $(".header").addClass("active"); } else { //remove the background property so it comes transparent again (defined in your css) $(".header").removeClass("active"); } }); }); 

And your css:

 .active { background-color: #fff} 

Make sure you also add this css rule, otherwise the background color will not change.

+10
source

Source: https://habr.com/ru/post/1212391/


All Articles