Home > Web Front-end > CSS Tutorial > How Can I Change an Image Source on Hover Using HTML, CSS, and JavaScript?

How Can I Change an Image Source on Hover Using HTML, CSS, and JavaScript?

Patricia Arquette
Release: 2024-12-23 00:24:10
Original
635 people have browsed it

How Can I Change an Image Source on Hover Using HTML, CSS, and JavaScript?

Modifying Image Source on Hover Using HTML, CSS, and JavaScript

To modify the source URL of an <img> tag upon hovering, various approaches can be taken.

CSS-Only (Webkit-Specific)

Using CSS alone, you can replace the image with a different URL on hover. However, it only works in Webkit-based browsers like Google Chrome:

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

Using a Div Background Image

Alternatively, you can use a

element with a background image replaced on hover:

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

Using JavaScript

With JavaScript, you can dynamically set the source of the <img> tag on mouseover and mouseout:

function hover(element) {
  element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');
}

function unhover(element) {
  element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');
}
Copy after login
<img>
Copy after login

The above is the detailed content of How Can I Change an Image Source on Hover Using HTML, CSS, and JavaScript?. 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