[javascript] Load Image from javascript

On my album slide show page, i have code like

<span style="display:none;">
   <img id="id1" src="~$imageUrl`" onload="javascript:showImage();">
</span>

<span>
    // show loader.
</span>

in showImage(), i am sure the image is loaded, so i show the image and hide the loader.

Now when user clicks on next, i need to change the src of the image. Now i need don't know how to set src only when image is loaded.

This question is related to javascript jquery

The answer is


Simplest load image from JS to DOM-element:

element.innerHTML += "<img src='image.jpg'></img>";

With onload event:

element.innerHTML += "<img src='image.jpg' onload='javascript:showImage();'></img>";

Try this.You have some symbols in $imageUrl

<img id="id1" src="$imageUrl" onload="javascript:showImage();">

You can try this:

<img id="id1" src="url/to/file.png" onload="showImage()">

function showImage() {
 $('#id1').attr('src', 'new/file/link.png');
}

Also, try to remove the ~, that is just the operator, that is needed for Server-Side (for example ASP.NET) you don't need it in JS.

This way, you can change the attribute for the image.

Here is the fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/


Sorry guys.

You can't rely on the image load event to fire but you can kind of rely on it in some situations and fallback to a maximum load time allowed. In this case, 10 seconds. I wrote this and it lives on production code for when people want to link images on a form post.

function loadImg(options, callback) {
  var seconds = 0,
  maxSeconds = 10,
  complete = false,
  done = false;

  if (options.maxSeconds) {
    maxSeconds = options.maxSeconds;
  }

  function tryImage() {
    if (done) { return; }
    if (seconds >= maxSeconds) {
      callback({ err: 'timeout' });
      done = true;
      return;
    }
    if (complete && img.complete) {
      if (img.width && img.height) {
        callback({ img: img });
        done = true;
        return;
      }
      callback({ err: '404' });
      done = true;
      return;
    } else if (img.complete) {
      complete = true;
    }
    seconds++;
    callback.tryImage = setTimeout(tryImage, 1000);
  }
  var img = new Image();
  img.onload = tryImage();
  img.src = options.src;
  tryImage();
}

use like so:

loadImage({ src : 'http://somewebsite.com/image.png', maxSeconds : 10 }, function(status) {
  if(status.err) {
    // handle error
    return;
  }
  // you got the img within status.img
}); 

Try it on JSFiddle.net

http://jsfiddle.net/2Cgyg/6/


this worked for me though... i wanted to display the image after the pencil icon is being clicked... and i wanted it seamless.. and this was my approach..

pencil button to display image

i created an input[file] element and made it hidden,

<input type="file" id="upl" style="display:none"/>

this input-file's click event will be trigged by the getImage function.

<a href="javascript:;" onclick="getImage()"/>
    <img src="/assets/pen.png"/>
</a>

<script>
     function getImage(){
       $('#upl').click();
     }
</script>

this is done while listening to the change event of the input-file element with ID of #upl.

_x000D_
_x000D_
   $(document).ready(function(){_x000D_
     _x000D_
       $('#upl').bind('change', function(evt){_x000D_
         _x000D_
    var preview = $('#logodiv').find('img');_x000D_
    var file    = evt.target.files[0];_x000D_
    var reader  = new FileReader();_x000D_
  _x000D_
    reader.onloadend = function () {_x000D_
   $('#logodiv > img')_x000D_
    .prop('src',reader.result)  //set the scr prop._x000D_
    .prop('width', 216);  //set the width of the image_x000D_
    .prop('height',200);  //set the height of the image_x000D_
    }_x000D_
  _x000D_
    if (file) {_x000D_
   reader.readAsDataURL(file);_x000D_
    } else {_x000D_
   preview.src = "";_x000D_
    }_x000D_
  _x000D_
    });_x000D_
_x000D_
   })
_x000D_
_x000D_
_x000D_

and BOOM!!! - it WORKS....


See this tutorial: Loading images with native JavaScript and handling of events for showing loading spinners

It tells you how to load images with native JavaScript and how to handle events for showing loading spinners. Basically, you create a new Image(); and handle the event correctly then. That should work in all browsers, even in IE7 (maybe even below IE7, but I did not test that...)


Use a new image object each time you want to load a picture :

var image = new Image();
image.onload = function () {
    document.getElementById('id1').setAttribute('src', this.src);
};
image.src = 'http://path/to/image';

just click on image and will change:

_x000D_
_x000D_
<div>_x000D_
 <img src="https://i.imgur.com/jgyJ7Oj.png" id="imgLoad">_x000D_
</div>_x000D_
_x000D_
<script type='text/javascript'>_x000D_
 var img = document.getElementById('imgLoad'); _x000D_
 img.onclick = function() { img.src = "https://i.imgur.com/PqpOLwp.png"; }_x000D_
 </script>
_x000D_
_x000D_
_x000D_


If you are loading the image via AJAX you could use a callback to check if the image is loaded and do the hiding and src attribute assigning. Something like this:

$.ajax({ 
  url: [image source],
  success: function() {
  // Do the hiding here and the attribute setting
  }
});

For more reading refer to this JQuery AJAX


<span>
    <img id="my_image" src="#" />
</span>

<span class="spanloader">

    <span>set Loading Image Image</span>


</span>

<input type="button" id="btnnext" value="Next" />


<script type="text/javascript">

    $('#btnnext').click(function () {
        $(".spanloader").hide();
        $("#my_image").attr("src", "1.jpg");
    });

</script>