0

I have an image element looking like this:

<img class="heroStr border" id="pictureId_<?php echo $row['id']; ?>" src="images/no_img.png" title="<?php echo $row['name']; ?>" data-src="<?php echo $row['imageUrl']; ?>" />

When the data-src has finished downloading the src are switched (the "no_img" src shows a temporary image until the real one has finished loading). It works perfectly with this code:

jQuery("#element img").load(function(){
    jQuery(this).attr('src', jQuery(this).data('src'));
}); 

What I want to do is remove the border class from the img when the image is loaded. I suppose I would just add jQuery(this).removeClass('border'); to the function but it doesn't work.

What is the correct way of doing this? Thanks!

— EDIT —

Added a jsfiddle you can use to try it out. What I'm trying to achieve now is to remove the border class when the data-src attribute has been loaded.

Cheezen
  • 179
  • 1
  • 2
  • 12

2 Answers2

0

The problem is that is an asynchronous call so you're trying to remove a class that actually does not exist yet. You can try to use .done() function.

steo
  • 4,586
  • 2
  • 33
  • 64
  • Thanks for the answer! Yeah, that's what I thought too. So how do I use the `.done()` function in this case? I'm not that good with jQuery, is it something like this? `jQuery("#element img").attr('data-src').done(function(){ jQuery(this).removeClass('border'); });` – Cheezen May 06 '13 at 14:43
  • It could work..but , are you using `.load` `function` because you're making an `AJAX` request? If so, `.done()` will do the trick. – steo May 06 '13 at 14:51
  • Couldn't get it to work... No, I'm retrieving images with a while loop using PHP. – Cheezen May 06 '13 at 15:17
0

for remove loading class of loaded images

just add this code at the end of <body>

let pending_images = document.querySelectorAll("img");
pending_images.forEach((img) => {
  let isLoaded = img.complete && img.naturalHeight !== 0;
  if (isLoaded) {
    img.classList.remove("loading");
  } else {
    img.addEventListener("load", (e) => {
      img.classList.remove("loading");
    });
  }
});

do not put this code in Domcontentloaded or $(document).ready()

Ali Afzali
  • 109
  • 7