I'm making a project in angular. I would like to add a navbar which have transparent background initially but on scroll it will change its color. I am using bootstrap classes for that
My Navbar heading is html code:
<nav class="navbar navbar-expand-md sticky-top">
...
</nav>
where can I add my Script to change its color on Scroll
You can achieve this with @HostListner
in your Typescript
file.
import { HostListener } from @angular/core;
@HostListener('window:scroll', ['$event'])
onWindowScroll() {
let element = document.querySelector('.navbar') as HTMLElement;
if (window.pageYOffset > element.clientHeight) {
element.classList.add('navbar-inverse');
} else {
element.classList.remove('navbar-inverse');
}
}
Put scroll event on HTML part.
<nav class="navbar navbar-expand-md sticky-top" (scroll)="onWindowScroll();"></nav>
$(function () {
$(document).scroll(function () {
var $nav = $(".navbar-fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
@import "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css";
body {
padding-top: 70px;
background: #ddd;
}
.navbar-fixed-top.scrolled {
background-color: #fff !important;
transition: background-color 800ms linear;
}
.navbar-fixed-top.scrolled .nav-link {
color:#555;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<nav id="navigation" class="navbar navbar-dark bg-primary navbar-fixed-top">
<ul class="nav navbar-nav">
<li class="nav-item"><a href="#" class="nav-link">Home</a></li>
<li class="nav-item"><a href="#projects" class="nav-link">Teams</a></li>
<li class="nav-item"><a href="#blog" class="nav-link">Service</a></li>
<li class="nav-item"><a href="#contact-us" class="nav-link">Contact us</a></li>
</ul>
</nav>
</header>
<h1>Folow</h1>
<p>
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
</p>
You Can See Here : See CodeExample
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