Deepak Malhotra
Deepak Malhotra

Reputation: 253

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.

Upvotes: 25

Views: 240266

Answers (11)

Mazen M.H.
Mazen M.H.

Reputation: 360

just click on image and will change:

<div>
	<img src="https://i.imgur.com/jgyJ7Oj.png" id="imgLoad">
</div>

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

Upvotes: 0

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>";

Upvotes: 0

Ande Caleb
Ande Caleb

Reputation: 1204

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.

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

   })

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

Upvotes: 0

Nabi
Nabi

Reputation: 2566

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...)

Upvotes: 0

Adassko
Adassko

Reputation: 5343

you can just append another hidden img element and swap them in onload event.

Or use single image element and use javascript like:

var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
    _img.src = this.src;
}
newImg.src = 'http://whatever';

this code should preload the image and show it when it's ready

Upvotes: 50

King Friday
King Friday

Reputation: 26106

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/

Upvotes: 7

user1636522
user1636522

Reputation:

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';

Upvotes: 7

Nikin Jasani
Nikin Jasani

Reputation: 51

<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>

Upvotes: 3

bruhbruh
bruhbruh

Reputation: 311

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

Upvotes: 2

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

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/

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Try this.You have some symbols in $imageUrl

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

Upvotes: 0

Related Questions