I am new to js and I been stuck on a problem on showing and hiding a div using js onscroll. I was able to figure that out fortunately but now my problem is when the div shows and hide it is very abrupt and I want it to fadein and out transition during its showing and hiding. I tried adding transition to it via css and into the js but nothing works. Please see my code below and hope you will be able to help me. Please know that I am trying to do this inside a WordPress site and adding the JS using a plugin WPCode Lite
This is my JS:
<script>
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (window.screen.width > 780) {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
var element = document.getElementById("headbar");
element.classList.remove("show");
element.classList.add("hide");
} else {
var element = document.getElementById("headbar");
element.classList.remove("hide");
element.classList.add("show");
}
}
}
</script>
This is my CSS:
#headbar {
transition: all .5s;
}
.hide {
opacity:0;
transition: all .5s;
}
.show {
opacity:1;
transition: all .5s;
}
I tried adding the transition via css and into js both did not work
2
Answers
Set a numeric
opacity
for#headbar
too so it can transitionExample:
I can’t see exactly what’s wrong with your code because it is incomplete … you did not include any of your HTML. But you don’t need separate hide and show classes … just add and remove a single class.