Home >Web Front-end >JS Tutorial >How to Programmatically Control the Image Source Attribute in JavaScript?
In the realm of web development, it is often necessary to dynamically modify the content of our pages. One common task is changing the source attribute of an image tag. Understanding how to accomplish this using JavaScript is essential for creating responsive and interactive web applications.
Using the HTML5 img tag, we can display an image on a web page. By accessing the src attribute of this tag, we can control the image that is displayed. Let's explore how to do this.
To programmatically alter the src attribute, we must first identify the img tag using its id or other unique identifier. Once we have a reference to the tag, we can use JavaScript to modify its src property.
For example, to change the src attribute of an img tag with an id of "myImage" to display a new image, we would use the following code:
<code class="javascript">document.getElementById("myImage").src = "new-image.jpg";</code>
In the given scenario, where an img tag's src attribute needs to be changed upon an event, we can leverage event listeners to trigger the source update. Let's say we want to swap the image when a user clicks on it.
<code class="html"><img id="edit-save" src="../template/edit.png" alt="Edit" onclick="changeImage()" /></code>
<code class="javascript">function changeImage() { document.getElementById("edit-save").src = "../template/save.png"; }</code>
By adding the onclick attribute to the img tag and associating it with a JavaScript function, we ensure that the image source is updated when the image is clicked.
The above is the detailed content of How to Programmatically Control the Image Source Attribute in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!