Home > Web Front-end > JS Tutorial > How Can I Dynamically Change Image Sources with jQuery on Click?

How Can I Dynamically Change Image Sources with jQuery on Click?

DDD
Release: 2024-12-20 19:16:11
Original
272 people have browsed it

How Can I Dynamically Change Image Sources with jQuery on Click?

Modifying Image Sources with jQuery

Your objective is to dynamically alter image sources within the following DOM structure:

<div>
Copy after login

Upon clicking each image, you desire to alter its source to "imgx_off.gif," where "x" corresponds to either "1" or "2."

Solution: Leveraging jQuery's attr() Function

Yes, it's feasible to accomplish this without CSS. jQuery's attr() method enables you to modify DOM element attributes, including image source URLs.

For instance, if your image tag posiada an id attribute of "my_image," the following code will do the trick:

<img>
Copy after login
$('#my_image').attr("src", "second.jpg");
Copy after login

To attach this action to a click event:

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

Image Rotation

If you want to rotate the images, use this code:

$('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 I Dynamically Change Image Sources with jQuery 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template