6

I'm trying to load an element only after the img element has been loaded, but I've tried everything I can think of and nothing is working. Right now I'm trying to see where the code stops working and I found that the alert I set up isn't running after the line I need the code to execute from.

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

The $img is defined within a function. The alert works at the document.ready line but not after the $img.load. I have tried to add eventlisteners, jquery .on, .load, and a bunch of others. I'm also calling the function to run within 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"
];
  • 1
    is the img being loaded dynamically via JavaScript? Or with an img html tag? – Jonathan.Brink Aug 04 '15 at 20:50
  • Is the image cached in the browser? – musically_ut Aug 04 '15 at 20:51
  • 1
    did you read the docs, especially "Caveats of the load event when used with images" http://api.jquery.com/load-event/ – Pevara Aug 04 '15 at 20:51
  • 2
    why are you wrapping it in the bubbleOnLoad function? is that function ever called? – trex005 Aug 04 '15 at 20:52
  • 1
    Why is there a $(document).ready(function() inside of function bubbleOnLoad? That seems very odd to me... – nurdyguy Aug 04 '15 at 20:57
  • 1
    The braces are unbalanced, which probably isn't helping. – Richard Poole Aug 04 '15 at 20:57
  • The braces within my code are correct, just maybe not on here. I have read and used every single doc known to man and nothing has worked. The image is being loaded dynamically with js, random image generator. The function is being called within the init function to get it to run. The document.ready within the function is the only thing that seems to be working. It may be strange, but I'm just trying to get to a working state at the moment. – Tiffany Haltom Aug 04 '15 at 21:06
  • @TiffanyHaltom can you post a more complete code. your current code is not giving any clue to us. – Arash Milani Aug 04 '15 at 21:10
  • Not sure what else is needed, I can post where the images are coming from, but I don't think that would be terribly helpful? – Tiffany Haltom Aug 04 '15 at 21:24

4 Answers4

4

You had some syntax errors in your code which I corrected and came up with this:

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

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

Here is the JSFiddle demo

Ahs N
  • 8,233
  • 1
  • 28
  • 33
  • Hmm. That doesn't seem to work, I had the same exact code at one point. only at the end when I called it, I used the shorthand for document.ready- $(bubbleOnLoad); – Tiffany Haltom Aug 04 '15 at 21:18
  • @TiffanyHaltom Please do give me more details about what is not really working. Because when I tested the code, the `#left-bubble` is shown only after the picture has been loaded – Ahs N Aug 05 '15 at 06:39
  • I'm really not sure what's not working, it could be because of the event bubbling, I'd have to work with more. As the code you wrote stands, the image loads, but the bubble does not, but it does work with the JSFiddle you gave. – Tiffany Haltom Aug 05 '15 at 15:29
  • None at all, which makes me think it has something to do with the event bubbling. I could be wrong. – Tiffany Haltom Aug 05 '15 at 15:37
2

In you code you are not even telling the browser it's supposed to run a code after image load. you should do something like this:

$(function(){

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

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

});

Also according to docs a common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree Can cease to fire for images that already live in the browser's cache
Arash Milani
  • 6,149
  • 2
  • 41
  • 47
  • I have this code for the image: ```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"; }```- and those are loaded with another function that is storing the images. – Tiffany Haltom Aug 04 '15 at 21:19
2

Try this jQuery plugin waitForImages

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>
alex
  • 479,566
  • 201
  • 878
  • 984
joyBlanks
  • 6,419
  • 1
  • 22
  • 47
  • You don't need to use the counter (in fact, currently it won't work), that function will be called only once *all* descendent images have loaded. Check the [docs](https://github.com/alexanderdickson/waitForImages/blob/master/README.md). – alex Aug 21 '15 at 04:58
0

You can only access the HTML element after it was created in DOM.
Also you need to check if the image was loaded before showing.
Thus your code need to look something as below:

$(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>
MaxZoom
  • 7,619
  • 5
  • 28
  • 44