skip to Main Content

I would like to put the load event on my img element.

When I check on the jQuery documentation for the load event, I can see:

enter image description here

If I put my event like this :

$( window ).on( "load", function() {
   // My window is loaded and I can see my img by console.log
   console.log('img');
});

But if I try as shown in the documentation:

$( "img" ).on( "load", function() {
    // My event is attached but it can't load the console.log
    console.log($(this));
});

How can I use the onload event on the img tag ?

Thanks for your help

2

Answers


  1. Chosen as BEST ANSWER

    Thanks, i think i found my problem.

    When my tag script is put on the head tag, and i put my load event on the document.ready, the load event is not trigger.
    It seems i have to cheack with image.comple first beacause the image is already loaded.

    But if i put my tag script at the end of the body, my event is trigger without the image.comple.

    Strange like behavior?

    For prevent the error best way is :

      if (img.complete) {
        // if complete do first
      } else {
        img.on('load', function(){
        // else put event and do my action when trigger
        }) ;
      }
    

  2. hope this can help 
    
    <img id="book" alt="Book" src="book.png">
    
    <script>
            const image = document.getElementById("book");               
         
            image.addEventListener("load", () => {
                console.log("image loaded successfully!");
            });
            
            image.addEventListener("error", () => {
                console.log("image loading error");
            });
            
        </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search