Home >Web Front-end >JS Tutorial >How Can I Dynamically Change Image Sources in My Web Application Using jQuery?
In web applications, dynamically controlling the visual appearance of elements is essential for engaging user experiences. One common scenario is the need to swap image sources based on user interactions.
Consider a scenario where a web page features two images:
<div>
You wish to change the image source to imgx_off.gif, where x represents the image number (1 or 2), when a user clicks on it. This functionality allows for visual representation of changes or state transitions.
jQuery's attr() function provides a versatile way to manipulate HTML attributes dynamically. In this case, it allows you to change the src attribute of the image.
To implement this functionality:
$('#img1').on({ 'click': function(){ $('#img1').attr('src','img1_off.gif'); } }); $('#img2').on({ 'click': function(){ $('#img2').attr('src','img2_off.gif'); } });
To enhance the functionality further, you can implement image rotation. This allows the images to seamlessly switch between two pre-defined states (e.g., from img1_on to img2_off and vice versa).
$('img').on({ 'click': function() { var src = ($(this).attr('src') === 'img1_on.jpg') ? 'img2_off.jpg' : 'img1_on.jpg'; $(this).attr('src', src); } });
This script checks the current src attribute of the clicked image and updates it with the appropriate image source based on the current state.
The above is the detailed content of How Can I Dynamically Change Image Sources in My Web Application Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!