How to run code after image upload using JQuery

I'm trying to load an element only after the img element has been loaded, but I've tried everything I can and nothing works. Right now I am trying to see where the code stops working and I found that the configured alert does not work after the line where I need the code to execute.

$img = $('#picture');
function bubbleOnLoad() {
  $(document).ready(function() {
    $img.load(function(){
    alert('document loaded')
    $('#left-bubble').show();
  })
})

      

$ img is defined inside a function. The warning works on the document.ready line, but not after $img.load

. I've tried adding eventlisteners, jquery.on, .load, and tons of others. I also call a function to execute inside my init function. Can someone explain to me why nothing is working?

function choosePic() 
 $('.speechbubble').hide();
 $('#picture').remove();
 var randomNum = Math.floor(Math.random() * samplePics.length);
 var img = new Image();
 img.onload = function() {
  $('.playing-field').prepend(img);
 handleImageLoad();
 }
 img.src = samplePics[randomNum];
 img.id = "picture";
}


var samplePics = 
 "assets/images/barack-obama.jpg",
 "assets/images/donald-trump_3.jpg",
 "assets/images/dt-2.jpg",
 "assets/images/bill-clinton.jpg",
 "assets/images/Rose-Byrne.jpg",
 "assets/images/pic.jpeg", 
 "assets/images/priest.jpg", 
 "assets/images/tb.jpg",
 "assets/images/test.jpg", 
 "assets/images/amy-poehler.jpg",
 "assets/images/stephen-colbert.jpg",
 "assets/images/aziz-ansari.jpg"
];

      

+3


source to share


4 answers


You had some syntax errors in your code that I fixed and came up with the following:

function bubbleOnLoad() {
    $img = $('#picture');
    $img.load(function () {
        alert('document loaded');
        $('#left-bubble').show();
    });
}

$(document).ready(function () {
    bubbleOnLoad();
});

      



Here is the JSFiddle daemon

+3


source


In your code, you don't even tell the browser to run the code after the image is loaded. you should do something like this:

$(function(){

  // DOM Content is ready, let interact with it.

  $('#picture').attr('src', 'image.jpg').load(function() {  
    // run code
    alert('Image Loaded');  
  });

});

      



Also according to the docs, a common problem that developers try to solve with the .load () shortcut is to execute a function when the image (or collection of images) is fully loaded. There are several known caveats to this that should be noted. It:

  • It doesn't work consistently or reliably, cross-browser
  • In WebKit, it does not work correctly if the src image src is set to the same src as before.
  • Improper DOM tree creation May stop firing for images that are already stored in the browser cache.
+1


source


Try this jQuery waitForImages plugin

https://github.com/alexanderdickson/waitForImages

//Javascript/jQuery
$(document).ready(function(){
  var counter = 0,totalImages= $('#preloader').find('img').length; 
  $('#preloader').find('img').waitForImages(function() {
    //fires for all images waiting for the last one.
    if (++counter == totalImages) {
      $('#preloader').hide();
      yourCallBack();
    }
  });
});
      

/*css*/
#preloader{
  position:absolute;
  top:-100px;/*dont put in DOM*/
}

#preloader > img{
  width:1px;
  height:1px;
}
      

<!--HTML [add the plugin after jQuery] -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.waitforimages/1.5.0/jquery.waitforimages.min.js" ></script>
 

<!--HTML [after body start] -->
<div id=preloader>
  <img src="1.jpg" />
  <img src="2.jpg" />
  <img src="3.png" />
  <img src="4.gif" />
  <img src="5.jpg" />
</div>
      

Run codeHide result


+1


source


You can only access the HTML element after it has been created in the DOM.
Also you need to check if the image is loaded before showing.
Thus, your code should look something like this:

$(document).ready(function() {
    bubbleOnLoad(); 
});
      
function bubbleOnLoad() {
    var newSrc = "https://lh5.googleusercontent.com/-lFNPp0DRjgY/AAAAAAAAAAI/AAAAAAAAAD8/Fi3WUhXGOY0/photo.jpg?sz=328";
    $img = $('#picture');
    $img.attr('src', newSrc) //Set the source so it begins fetching
      .each(function() {
          if(this.complete) {
            alert('image loaded')
            $('#left-bubble').show();
          }
      });
 }
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left-bubble" style="display:none">
  <img id="picture"/>
</div>
      

Run codeHide result


0


source







All Articles