Aleksa Ristic
Aleksa Ristic

Reputation: 2499

On src change even if src is not valid

I have simple image like this:

<img id="ddd" src="/someimage.jpg" /> <!-- valid image -->

Now on button click i change it like this:

<script>
    function Change() {
        $("#ddd").prop("src", "/someOtherImage.jpg"); <!-- valid image -->
    }
</script>

and besides that i listen to when it is changed like this:

<script>
    $(function() {
        $("#ddd").on("load", function() {
            alert("changed");
        });
    });
</script>

and like this it works but it doesn't work when i set it to invalid image like this:

<script>
    function Change1() {
        $("#ddd").prop("src", "/savsavsa.jpg"); <!-- invalid image -->
    }
</script>

or

<script>
    function Change1() {
        $("#ddd").prop("src", "none"); <!-- invalid image -->
    }
</script>

or

<script>
    function Change1() {
        $("#ddd").prop("src", "#"); <!-- invalid image -->
    }
</script>

in none of 3 above chages it fires load event. I tried with change event but also not working. When i inspect that img it does change.

Upvotes: 2

Views: 50

Answers (3)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

It does not make sense to listen load event on invalid image. Since there's no image, there would be no load event.

If you primarily want to check for src attribute change, then you may trigger custom event:

var imgSrc = null;
$(function(){
  var imageSrc = $('#ddd').attr('src');
  if (imageSrc != imgSrc) {
   $('#ddd').trigger('srcChange');
  }
})

// listen for the change:
$('#ddd').on('srcChange', function() {
  console.log('src changed');
});

If you want to check src attribute change on occurrence then you may store old value in localStorage and check for the change with that value or check for the change by triggering on interval.

Upvotes: 0

D. Pardal
D. Pardal

Reputation: 6597

In most cases, the error event will be fired if the image source points to an invalid resource, so you can use:

function srcChangedListener() {
    alert("changed");
}
$(function() {
    $("#ddd").on("load", srcChangedListener);
    $("#ddd").on("error", srcChangedListener);
});

However, these events will only fire after the resource is fetched from the server. If you want a faster approach, use MutationObserver.

Upvotes: 2

Quentin
Quentin

Reputation: 943561

The load event fires when the image loads, not when the src is changed.

If you change the src to something that doesn't make an image load successfully then it is natural that there is no load event.

Try the error event instead.

Upvotes: 2

Related Questions