This is as far as I managed to go.
Background-image is set with inline css on container (is not working otherwise).
How can I have any kind of smooth transition between the image change?
function onmouseover(){
// alert("Hello! I am an alert box!!");
var element = document.getElementById('conf');
element.style.backgroundImage = "url('/imgs/jpg/stats.jpg')";
}
function onmouseout(){
// alert("Hello! I am an alert box!!");
var element = document.getElementById('conf');
element.style.backgroundImage = "url('/imgs/jpg/welcome_back.jpg')";
}
This code is actually changing the background-image that is already set. This transaction is happening very fast and sharp
background is one of the animatable CSS properties so you can set a transition on it.
This snippet uses the code given in the question with an element with id conf which has a subdiv element on which you can hover. The main thing that has been set is:
transition: background-image 1s linear;
in conf so the backgrounds change over smoothly.
const conf = document.getElementById('conf');
const subdiv = document.getElementById('subdiv');
subdiv.addEventListener('mouseover', onmouseover);
subdiv.addEventListener('mouseout', onmouseout);
function onmouseover() {
// alert("Hello! I am an alert box!!");
var element = document.getElementById('conf');
element.style.backgroundImage = "url('https://picsum.photos/id/1015/200/300')";
}
function onmouseout() {
// alert("Hello! I am an alert box!!");
var element = document.getElementById('conf');
element.style.backgroundImage = "url('https://picsum.photos/id/1016/200/300')";
}
#conf {
transition: background-image 1s linear;
width: 50vw;
height: 50vw;
background-image: url('https://picsum.photos/id/1016/200/300');
background-size: cover;
}
#subdiv {
width: 20vw;
height: 20vw;
background-color: yellow;
font-size: 30px;
}
<div id="conf">
<div id="subdiv">Hover over me</div>
</div>
You can achieve this only with HTML and CSS using the transition property
img {
position:absolute;
transition: opacity 1s ease-in-out;
}
img.top:hover {
opacity:0;
}
<img src="https://picsum.photos/id/237/200/300" /><img class="top" src="https://picsum.photos/id/238/200/300" />