I made a function in which an image’s src
changes as I scroll the page.
window.addEventListener("scroll", function () {
var textPartitionsCercleDiv = document.getElementById("text-partitions-cercle")
var textPartitionsDistanceFromTop = textPartitionsCercleDiv.getBoundingClientRect().top
var texteMichelle = document.getElementById("michelle-text")
var texteMichelleTop = texteMichelle.getBoundingClientRect().top * 0.2
if (texteMichelleTop > 200) {
document.getElementById("img-partitions").src = "partition-cercle2.png";
} else {
document.getElementById("img-partitions").src = "partition-cercle1.png";
}
})
Where in the CSS should I add the transition
property so it changes smoothly from one image to another? Everything I’ve tried didn’t work properly.
I would have structured it differently.
Insert the two images and give them each different class. Using Jquery/javascript to trigger the new class which makes the transition.
$(document).ready(function() {
$("#eb_onclick").click(function() {
$("#mycontainer img.top").toggleClass("transparent");
});
});
#mycontainer {
position:relative;
height:281px;
width:450px;
margin:0 auto;
}
#mycontainer img {
position:absolute;
left:0;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
#mycontainer img.transparent {
opacity:0;
}
#eb_onclick {
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="eb_onclick" >Click me to toggle</button>
<div id="mycontainer" class="shadow">
<img class="bottom" height="100px" src="https://cdn.pixabay.com/photo/2018/07/26/07/45/valais-3562988_960_720.jpg" />
<img class="top" height="100px" src="https://cdn.pixabay.com/photo/2020/06/26/17/16/daisies-5343423_960_720.jpg" />
</div>