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
Linda HamiltonOriginal
2024-12-16 18:51:14524browse

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 alt="How Can I Change an Image Source on Hover?" > 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');
}

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 alt="How Can I Change an Image Source on Hover?" > tag with a

tag. By setting the background image of the
and modifying it on hover, you can effectively achieve the desired result:
<div>
<pre class="brush:php;toolbar:false">#my-div {
    background-image: url('http://dummyimage.com/100x100/000/fff');
}

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

The JavaScript Solution

For the most versatility, you can leverage JavaScript to directly manipulate the src attribute of the <img alt="How Can I Change an Image Source on Hover?" > tag. This approach works across all major browsers:

<img  alt="How Can I Change an Image Source on Hover?" >
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');
});

By employing one of these techniques, you can seamlessly change the source URL of an <img alt="How Can I Change an Image Source on Hover?" > 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!

Statement:
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
Previous article:How Can I Tightly Pack Inline Elements in HTML Without Sacrificing Readability?Next article:How Can I Tightly Pack Inline Elements in HTML Without Sacrificing Readability?

Related articles

See more