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
Release: 2024-10-30 19:08:03
Original
654 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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