Home >Web Front-end >JS Tutorial >How Can I Dynamically Change Image Sources in My Web Application Using jQuery?

How Can I Dynamically Change Image Sources in My Web Application Using jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 08:57:13246browse

How Can I Dynamically Change Image Sources in My Web Application Using jQuery?

Manipulating Image Sources with 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.

Solution Using jQuery's attr()

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:

  1. Assign a unique id to each image, such as img1 and img2.
  2. Use the attr() function to change the src attribute when the image is clicked.
$('#img1').on({
    'click': function(){
        $('#img1').attr('src','img1_off.gif');
    }
});
$('#img2').on({
    'click': function(){
        $('#img2').attr('src','img2_off.gif');
    }
});

Rotation of Image Sources

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!

Statement:
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