Home > Web Front-end > CSS Tutorial > How Can I Change an Image Source on Hover?

How Can I Change an Image Source on Hover?

Linda Hamilton
Release: 2024-12-16 18:51:14
Original
358 people have browsed it

How Can I Change an Image Source on Hover?

Change Image Source on Hover: A Comprehensive Guide

You may encounter a scenario where you need to dynamically change the source URL of an <img> tag when the mouse hovers over it. While it seems like a straightforward task, it's not as easily achievable as one might think.

The CSS Pitfall

Initially, you might try using CSS's content property to replace the image source, as seen in the following code:

#my-img:hover {
    content: url('http://dummyimage.com/100x100/eb00eb/fff');
}
Copy after login

However, this approach only works for Webkit browsers like Google Chrome. Other major browsers, such as Firefox and Safari, ignore the content property in this context.

The HTML and CSS Alternative

If CSS is not an option, you can consider replacing the <img> tag with a <div> tag. By setting the background image of the <div> and modifying it on hover, you can effectively achieve the desired result:

<div>
Copy after login
#my-div {
    background-image: url('http://dummyimage.com/100x100/000/fff');
}

#my-div:hover {
    background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
Copy after login

The JavaScript Solution

For the most versatility, you can leverage JavaScript to directly manipulate the src attribute of the <img> tag. This approach works across all major browsers:

<img>
Copy after login
const myImg = document.getElementById('my-img');

myImg.addEventListener('mouseover', () => {
    myImg.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');
});

myImg.addEventListener('mouseout', () => {
    myImg.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');
});
Copy after login

By employing one of these techniques, you can seamlessly change the source URL of an <img> tag on hover, providing dynamic and engaging visual experiences for your web applications.

The above is the detailed content of How Can I Change an Image Source on Hover?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template