It's recommended to refrain from utilizing inline styles in JavaScript unless absolutely necessary or if achieving the desired functionality is challenging through other means. Consider using .classList.toggle()
(or .toggleClass()
with jQuery) instead. For a smoother transition, such as adjusting opacity, apply transition: opacity 0.3s;
, and for multiple properties, separate the timings with commas like so:
transition: opacity 0.3s, background-color 0.3s;
Implementing Changes with JavaScript
const elRibbon = document.querySelector("#ribbon");
addEventListener("scroll", () => {
const isShowRibbon = scrollY > 500;
elRibbon.classList.toggle("is-visible", isShowRibbon);
}, { passive: true });
* { margin: 0; box-sizing: border-box; }
body {
min-height: 300vh; /* used to trigger scrollbar */
}
#ribbon {
padding: 2rem;
background: #f00;
position: fixed;
width: 100%;
opacity: 0;
transition: opacity 0.3s;
}
#ribbon.is-visible {
opacity: 1;
}
<div id="ribbon">Ribbon</div>
Scroll past 500px to display the ribbon!
Utilizing jQuery Functionality
const $ribbon = $('#ribbon');
$(window).on("scroll", function() {
const isShowRibbon = $(this).scrollTop() > 500;
$ribbon.toggleClass("is-visible", isShowRibbon);
});
* {
margin: 0;
box-sizing: border-box;
}
body {
min-height: 300vh; /* used to trigger scrollbar */
}
#ribbon {
padding: 2rem;
background: #f00;
position: fixed;
width: 100%;
opacity: 0;
transition: opacity 0.3s;
}
#ribbon.is-visible {
opacity: 1;
}
<div id="ribbon">Ribbon</div>
Scroll past 500px to show the ribbon!
<script src="https://code.jquery.com/jquery-3.6.3.js"></script>
Avoid excessive querying of DOM elements within resource-intensive callbacks like on scroll events. Instead, store references to the elements you intend to modify beforehand in variables like elRibbon
and then manipulate them inside the callback.