I use a secondary fille called custom.css to overwrite the bootstrap code and I would like to know how to create a code that is activating only when the visitor of my site is not in the very top of the page.
Until now I created a transparent navbar using the default code provided by bootstrap. The only thing I have to do is to set it to execute: background-color: #color
when the visitor is scrolling down.
Example: https://www.lyft.com/
When I am in the top of the page, the navbar is transparent, but when I scroll down it becomes opaque.
Creating a transparent navbar is very easy - just don't add a color class . bg-* to the navbar.
For instance, if you would like the navbar to be more transparent, you need to lower the opacity coefficient from rgba(255, 255, 255, 0.2). The coefficient is currently 0.2 and you can increase or decrease its value according to your needs.
background-color: rgba(0,0,0,0.0) will work.
To create the rendering of the background color change of the navbar you will have to create a useEffect where you will pass the changeBackground function and an event listener that will be on scroll and passing the changeBackground function, like so.
Ok you need the following code to achieve this effect: (I am going to use jQuery as it is the bootstrap supported language).
jQuery:
/**
* Listen to scroll to change header opacity class
*/
function checkScroll(){
var startY = $('.navbar').height() * 2; //The point where the navbar changes in px
if($(window).scrollTop() > startY){
$('.navbar').addClass("scrolled");
}else{
$('.navbar').removeClass("scrolled");
}
}
if($('.navbar').length > 0){
$(window).on("scroll load resize", function(){
checkScroll();
});
}
You can also use ScrollSpy
to do this.
and your CSS (example):
/* Add the below transitions to allow a smooth color change similar to lyft */
.navbar {
-webkit-transition: all 0.6s ease-out;
-moz-transition: all 0.6s ease-out;
-o-transition: all 0.6s ease-out;
-ms-transition: all 0.6s ease-out;
transition: all 0.6s ease-out;
}
.navbar.scrolled {
background: rgb(68, 68, 68); /* IE */
background: rgba(0, 0, 0, 0.78); /* NON-IE */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With