Home >Web Front-end >JS Tutorial >How Can jQuery Be Used to Dynamically Change Image Sources on Click?
Using jQuery to Alter Image Sources
Within a web structure like:
<div>
when users click on an image, you're tasked with updating its source to imgx_off.gif, where x represents the image number.
Is jQuery capable of handling this task, or is CSS the preferred method?
Using jQuery's attr() Function
jQuery provides the attr() function, allowing you to modify attribute values. To change an image's source with an ID of my_image:
$('#my_image').attr('src', 'second.jpg');
Event-Based Image Change
Connect this code to a click event:
$('#my_image').on({ 'click': function(){ $('#my_image').attr('src','second.jpg'); } });
Image Rotation
To implement image rotation:
$('img').on({ 'click': function() { var src = ($(this).attr('src') === 'img1_on.jpg') ? 'img2_on.jpg' : 'img1_on.jpg'; $(this).attr('src', src); } });
The above is the detailed content of How Can jQuery Be Used to Dynamically Change Image Sources on Click?. For more information, please follow other related articles on the PHP Chinese website!