Home > Article > Web Front-end > How can I dynamically change an image source using JavaScript on click?
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!