I'd be inclined to toggle a class on the body element, and use CSS to control the colours. For example:
$(function() {
$(window).on("scroll", function() {
$("body").toggleClass("scrolled", $(document).scrollTop() > 50);
})
});
#main-nav{
background: transparent;
transition: background 0.3s;
}
.scrolled #main-nav {
background: black;
}
Demo[
^]
Edit: If you can drop support for Internet Explorer, you can use the Intersection Observer API to make this slightly more efficient:
$(function() {
const scrollPoint = 50;
let targetPixel = document.createElement("div");
targetPixel.style.cssText = `
position: absolute;
top: ${scrollPoint}px;
left: 0;
width: 1px;
height: 1px;
`;
targetPixel = document.body.appendChild(targetPixel);
const observer = new IntersectionObserver(entries => {
const scrolled = entries[0].boundingClientRect.y < 0;
if (scrolled) {
document.body.classList.add("scrolled");
} else {
document.body.classList.remove("scrolled");
}
});
observer.observe(targetPixel);
});
Demo[
^]
Intersection Observer API - Web APIs | MDN[
^]