user8060797
user8060797

Reputation: 11

JQuery changing image

Hi I have this problem: when a value is selected in a select field the "src" attribute of an image is changed. I need to get the src value of that image AFTER is changed by jquery.

I do this:

jQuery(document).ready(function( $ ) {

    $('.woocommerce-main-image img').on('change', function() {
        var a = $('.woocommerce-main-image img').attr('src');
    });
});

But in this way I get the src BEFORE the change. How can I get the src value after changing?

Upvotes: 0

Views: 84

Answers (3)

Dhaval Pankhaniya
Dhaval Pankhaniya

Reputation: 1996

you can use load event

$('.woocommerce-main-image img').on('load', function () {
    alert($(this).attr('src'));
});

check this link for more information

Upvotes: 0

Bastien Ho
Bastien Ho

Reputation: 829

You should try to use the current object instead of the global selector, like this:

jQuery(document).ready(function( $ ) {

  $('.woocommerce-main-image img').on('change', function() {

    var a = $(this).attr('src');

  });

});

Upvotes: 0

Nisarg Shah
Nisarg Shah

Reputation: 14541

Instead of change you should be listening to load event.

According to MDN:

This event handler will be called on the image element when the image has finished loading. This applies whether the image is applied via the src attribute or the list-style-image style property. If you change the image, the event will fire again when the new image loads. This event will not bubble up the element tree.

$("#img1").on("load", function(){
  console.log($(this).attr('src'));
});

setTimeout(function() {
  $("#img1").attr("src", "//placehold.it/200");
},5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="//placehold.it/150" id="img1" />

Upvotes: 2

Related Questions