How to Change the Image Source Using jQuery ?

How to Change the Image Source Using jQuery ?

Asked on November 2, 2018 in jQuery.
Add Comment


  • 1 Answer(s)

    You can use jQuery’s attr() function. For example, if your img tag has an id attribute of ‘my_image’, you would do this:

    <img id="my_image" src="first.jpg"/>

    Then you can change the src of your image with jQuery like this:

    $("#my_image").attr("src","second.jpg");

    To attach this to a click event, you could write:

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

    To rotate the image, you could do this:

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

     

    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.