Home >Web Front-end >CSS Tutorial >How to Change Images on Click Without Extensive JavaScript?

How to Change Images on Click Without Extensive JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 15:53:02643browse

How to Change Images on Click Without Extensive JavaScript?

Changing Images on Click: A Simple Approach

When faced with the task of dynamically swapping images on click events, one may initially resort to JavaScript or jQuery for a swift solution. However, for simpler scenarios, there is an alternative that avoids the need for extensive JavaScript code.

To change images with ease, consider adding unique IDs to your image elements, as seen below:

<ul>
  <li><img src="image1.png">

Next, create a simple JavaScript function to handle the image swap on click:

function changeImage(image) {
  // Get the current image source
  let currentSrc = image.src;

  // Replace the source with the new image
  const newSrc = currentSrc.replace(".png", "_colored.png");
  image.src = newSrc;
}

In this function, the current image source is retrieved and replaced with a new source that includes "_colored" in its name.

Finally, add the onclick event listener to each image to call the changeImage() function when clicked:

<ul>
  <li><img src="image1.png">

With this approach, images can be seamlessly swapped on click without the need for complex JavaScript or pseudo selectors.

The above is the detailed content of How to Change Images on Click Without Extensive 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