Home >Web Front-end >JS Tutorial >How can I dynamically change an image source using JavaScript on click?

How can I dynamically change an image source using JavaScript on click?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 19:08:03652browse

How can I dynamically change an image source using JavaScript on click?

Dynamically Modifying Image Source Using JavaScript

In web development, it may be necessary to change the source attribute of an image tag (img tag) programmatically to display different images based on user interaction or dynamic content. To achieve this, JavaScript provides various methods to manipulate HTML elements.

Consider the following scenario:

<img src="../template/edit.png" name="edit-save" alt="How can I dynamically change an image source using JavaScript on click?"><br>

Initially, the image tag displays an image with the source "edit.png." The goal is to change this source to "save.png" upon clicking the image. To achieve this, an HTML a tag with an onclick event handler can be used, as shown below:

<a href="#" onclick="edit()"><img src="../template/edit.png" id="edit-save" alt="How can I dynamically change an image source using JavaScript on click?"></a><br>

The edit() function can then be implemented in JavaScript to perform the desired source modification:

function edit()<br>{<pre class="brush:php;toolbar:false">var inputs = document.myform;
for(var i = 0; i <p>}<br></p>

By assigning an id to the image tag ("edit-save" in this case), the JavaScript code can access and modify its src attribute. The snippet provided retrieves the HTML element by id and sets its src attribute to the desired source, effectively changing the displayed image.

It's worth noting that the original code you provided attempted to handle the src modification within the edit() function, which led to the issue of requiring two clicks to change the source. By separating the image source manipulation into a separate step, you can avoid this inconvenience and ensure that the image source changes immediately upon the first click.

The above is the detailed content of How can I dynamically change an image source using JavaScript on click?. 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