I would like to change the src picture of an image (or use some other technique?) in my fixed menu bar when I scroll down.
Here is my html:
<header>
<a href="/">
<img src="img1.jpg" width="200px" height="100px">
</a>
</header>
<main>
...
The header is fixed. So it stays on the top of the page during scrolling all the time.
Now, I would like to transition (if that's possible with the Alpine's x-show.transition or CSS's transition?) when I start scrolling.
So, when I start scrolling the image is starting to get smaller to the new image dimension and then being fade out and fade in replaced with the new image img2.jpg with the new dimensions width="150px" and height="80px".
How to do that in pure Alpine js?
I don’t have any experience with Alpine JS, so i solved this with CSS and standard JS.
Start by giving your img object an id, then add the styling below to the object.
#img {
transition: .5s;
}
I used a scroll-listener and checked the scrollvalue.
const elem = document.getElementById("img");
window.onscroll = function() {
if(window.scrollY>=40){
//user scrolled to the top of the page
elem.style.height = "80px";
elem.style.width = "150px";
} else {
//user scrolled to the top of the page
elem.style.height = "100px";
elem.style.width = "200px";
}
};