I'm trying to apply a mouseover event to change an original image to new image, and then back to the original image upon mouseout. However, the original image files are very large, so I'm using a container class to display them in the size I want.
The problem is that when I hover over the image, it displays the new image, but it's at the original size instead of being within the constraints of the container.
const imageContainer = document.querySelector('.flex-container');
const image = document.getElementById('bookCover2');
const originalSrc = 'Book_2_Cover.png';
const newSrc = 'Book_2_Back.png';
imageContainer.addEventListener('mouseover', () => {
image.src = newSrc;
});
imageContainer.addEventListener('mouseout', () => {
image.src = originalSrc;
});
Set the width and height of the img element to match the container, and ensure the images do not exceed those dimensions:-
Add this or change your CSS to:-
.flex-container img {
width: 100%; /* or a fixed width like 300px */
height: auto; /* maintain aspect ratio */
object-fit: contain; /* or cover, depending on how you want the images to scale */
max-width: 100%; /* prevent image overflow */
max-height: 100%; /* optional: constrain height */
}
Your javascript look ok though.