Reputation: 3
I want an image to change when it is hovered on. So far my code is fine. But I want the image to change back to its original image when mouse leaves the image. This is where my code doesn't work properly. What is the problem and how can I fix it? I really appreciate your help.
This is my html code:
<div onmouseover="show_large(this);" onmouseout="show_normal(this);">
<img src="2.JPG">
</div>
<script>
function show_large(element){
element.innerHTML=
'<img src="1.JPG">';
}
function show_normal(element){
element.innerHTML=
'<img src="2.JPG">';
}
</script>
And this is my css code:
div{
width: 25%;
margin: 0;
}
img{
width: 100%;
margin: 0;
}
Upvotes: 0
Views: 155
Reputation: 152
You can achive this only with CSS and HTML, just add background-image
property on your div and change img on :hover
, like so:
div{
background-image: url('first-img-src.png');
transition: background-image 1s ease-in-out;
}
div:hover{
background-image: url('second-img-src.png');
}
EDIT:
You can achive same thing using mouseenter
and mouseleave
with changeing img.src
property:
const img = document.querySelector('img');
img.addEventListener('mouseenter', (e) => {
img.src = 'second.png'
})
img.addEventListener('mouseleave', (e) => {
img.src = 'first.png'
})
Upvotes: 2
Reputation: 666
You can simply do it using css it self. working jsFiddle
.image-container{
width: 300px;
}
.over{
display: none;
}
.image-container:hover .main{
display: none;
}
.image-container:hover .over{
display: block;
}
<div class="image-container">
<img class="main" src="https://www.rd.com/wp-content/uploads/2019/04/shutterstock_1013848126.jpg" width="100%" />
<img class="over" src="https://www.rd.com/wp-content/uploads/2019/05/shutterstock_671541538-e1557714950453.jpg" width="100%" />
</div>
Upvotes: 0
Reputation: 1432
Since images will have default hover events, you need to disable them for it to work on the parent div. You can disable them by adding pointer-events: none
to img
tag
function show_large(element) {
element.innerHTML =
'<img src="https://randomuser.me/api/portraits/men/51.jpg">';
}
function show_normal(element) {
element.innerHTML =
'<img src="https://randomuser.me/api/portraits/men/50.jpg">';
}
div {
width: 25%;
margin: 0;
}
img {
width: 100%;
margin: 0;
pointer-events: none;
}
<div onmouseover="show_large(this);" onmouseout="show_normal(this);">
<img src="https://randomuser.me/api/portraits/men/50.jpg">
</div>
Upvotes: 1