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

How to Change an Image Source URL on Hover Using HTML, CSS, and JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 15:20:11925browse

How to Change an Image Source URL on Hover Using HTML, CSS, and JavaScript?

Changing Image Source URL on Hover

Problem:

You want to dynamically update the source URL of an <img> tag when the user hovers over it.

Attempt and Issue:

Your initial approach using CSS's content property and :hover selector didn't work.

Solution:

While changing the src attribute directly with CSS is not possible, here are two alternative methods using HTML, CSS, and JavaScript:

Method 1: Using Background Images

  1. Replace the <img> tag with a <div> tag.
  2. Set the background image of the <div> to the default image using CSS.
  3. Use the :hover selector to update the background image to the hover image.
<div>
#my-div:hover {
    background: url(hover-image.jpg);
}

Method 2: Using JavaScript

  1. Define JavaScript functions to change the src attribute on hover and unhover.
  2. Assign the hover function to the onmouseover event and the unhover function to the onmouseout event of the <img> tag.
<img>
function hoverImage(element) {
    element.src = "hover-image.jpg";
}

function unhoverImage(element) {
    element.src = "default-image.jpg";
}

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