Home > Web Front-end > JS Tutorial > How Can I Change an Image Source Using jQuery?

How Can I Change an Image Source Using jQuery?

Linda Hamilton
Release: 2024-12-23 02:38:42
Original
615 people have browsed it

How Can I Change an Image Source Using jQuery?

Modifying Image Source with jQuery

In a webpage, suppose you have an HTML structure with two images, each having "imgx_on.gif" as their source, where "x" represents an image number (1 or 2). Upon clicking an image, you wish to modify its source to "imgx_off.gif".

Solution with jQuery

Utilizing jQuery's attr() function, you can alter the source attribute of an image. To achieve this, assign an id attribute to your image (for instance, "my-image") and execute the following code:

$('#my-image').attr('src', 'imgx_off.gif');
Copy after login

Example for Image Rotation

To rotate images, you can employ the following jQuery code:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.gif')
            ? 'img2_on.gif'
            : 'img1_on.gif';
         $(this).attr('src', src);
    }
});
Copy after login

This code alternates the source of the clicked image between "img1_on.gif" and "img2_on.gif".

The above is the detailed content of How Can I Change an Image Source Using jQuery?. 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