Home > Web Front-end > JS Tutorial > How Can jQuery Be Used to Dynamically Change Image Sources on Click?

How Can jQuery Be Used to Dynamically Change Image Sources on Click?

Patricia Arquette
Release: 2024-12-04 09:17:11
Original
540 people have browsed it

How Can jQuery Be Used to Dynamically Change Image Sources on Click?

Using jQuery to Alter Image Sources

Within a web structure like:

<div>
Copy after login

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');
Copy after login

Event-Based Image Change

Connect this code to a click event:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});
Copy after login

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);
    }
});
Copy after login

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!

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