I'm trying to load an image into a div using JavaScript. Below is the current snippet of the code.
window.onload=function image_show() {
var thumbContainer = document.getElementById("art_img");
var thumbnail = document.createElement("img");
var img_width = document.getElementById("art_img").offsetWidth;
var img_height = document.getElementById("art_img").offsetHeight;
thumbnail.onload=function() {
thumbContainer.appendChild(thumbnail);
}
thumbnail.src = "http://xyz/bkg.png";
thumbnail.width = img_width;
thumbnail.height = img_height;
setTimeout(image_show, 1000 );
}
The appendChild() method keeps appending the images (one below the other) after the Timeout. But I want to actually keep refreshing the div with the same image.
The source of the image will be updated on my website with the same name, and I want the script to display the new image after Timeout. I tried inserting a removeChild() method just before appendChild(), but didn't work as expected. Any help will be appreciated.
just empty the element before you append again
thumbnail.onload=function() {
thumbContainer.innerHTML = ""; // ADD THIS LINE
thumbContainer.appendChild(thumbnail);
}
The problem is that the browser caches the image.
Try appending a timestamp to the src attribute of the thumbnail:
thumbnail.src = "http://xyz/bkg.png?ts=" + Date.now();
This way, the source URL will be slightly different each time the image_show function runs and the picture should be loaded by the browser each time.
Related
Hi how do I insert a image on a specific page when users visit my site?
I want to show an image when users visit the url: http://ww.exsample.com/order/cart/
It can be done with java script but how exactly?
Is it as simple as this:
if(document.URL.indexOf("order/cart/") >= 0){
var image = new Image; image.src ="http://www.exsample.com/images/wow.jpg"
}
Thanks alot
You are missing the important step where you actually append the image to the document.
var image = new Image;
image.src ="http://www.exsample.com/images/wow.jpg";
// the last step needed:
document.body.appendChild(image);
Sidenote:
Using document.URL is okay, however I prefer document.location. In your case you could use document.location.pathname which would return only the path /order/cart/.
Edit:
To put the image into a div, you simple create an additional div:
if(document.URL.indexOf("order/cart/") >= 0){
// create the wrapper div
var e = document.createElement("div");
// create the image and set the source
var image = new Image();
image.src ="http://lorempixel.com/400/200"
// append the image to the div
e.appendChild(image);
// and finally append the div to the document
document.body.appendChild(e);
}
I have a page that swaps some fairly large images in and out. There are too many to preload when the page initially loads so that is not an option. So what I need to do is load them as they are requested by the user. Right now I'm using jQuery to replace the img's src. This works fine but the images I am loading can be around 500KB and it looks bad as they paint down the screen as they are downloading. What I'd like to do is pop a loading gif on the page when the image is in the process of loading then have the loading gif disappear once the image is loaded. I'm struggling to find a way to do that though. Here is the JS/jQuery code that I have that just replaces the src.
var product = "bowl";
var image = "dog.jpg"; //this is actually pulled from a data attribute, but its just hardcoded here for an example
$("#images img[data-product="+product+"]").attr("src", "/img/tablesetting/"+image);
I made a working jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
I recently needed to do the same thing. Basically I wrapped the image in a container div. within the container I've added a span element with my ajax loader gif embedded. this span has to be hidden initially but gets visible when an ajax request is made. The span gets removed when the image is fully loaded.
before ajax call
$('#your_image_container').find('span').show();
on success
$('#your_image').attr('src', 'your/image/url').load(function() {
$('#your_image_container').find('span').fadeOut();
});
I made a jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
Preload the image.
var product = "bowl";
var imageSrc = "dog.jpg";
var imgEl = $("#images img[data-product="+product+"]");
// show loading graphic only if it's needed
var timer = setTimeout(function(){
imgEl.attr("src", "/img/loading.gif");
},50);
// preload image
var img = new Image();
img.onload = function() {
clearTimeout(timer);
imgEl.attr("src",imageSrc);
}
img.src = imageSrc;
$img.attr("src", newImage);
if (!$img.get(0).complete) {
$img
.hide()
.after("<img src=throbber>")
.on("load", function () {
$(this).show().next().remove();
});
}
I created a js file and created a function and what it supposed to do is change the image once everytime my page is loaded..
function swapPic() {
var imgSrc = [];
imgSrc[0] = "/Content/Resources/cafe1.jpg";
imgSrc[1] = "/Content/Resources/cafe2.jpg";
imgSrc[2] = "/Content/Resources/cafe3.jpg";
imgSrc[3] = "/Content/Resources/cafe4.jpg";
imgSrc[4] = "/Content/Resources/cafe5.jpg";
imgSrc[5] = "/Content/Resources/cafe6.jpg";
var randomnumber = Math.floor(Math.random() * 5);
var img = document.getElementById("imgContainer");
img.setAttribute("src", imgSrc[randomnumber]);
// alert("ok");
}
In my html code, in my img tag:
<img id="imgContainer" src="~/Content/Resources/cafe3.jpg" onload="swapPic()"/>
Adding the alert("ok") line and i reload the page once, the alert window keeps popping up and the image changes. I keep closing the window, and it still pop ups and the image changes. It just stopped after some time.
So I guess, during the time i did not include that alert("ok") line, my function is continuously called and stop. It just happen so fast which makes it look like fine.
I think this is a problem. Do you have any idea guys how can I make sure that my function is just called once?
You should add onloadon the body, not the img.
<body onload="swapPic();">
<img id="imgContainer" src="~/Content/Resources/cafe3.jpg"/>
</body>
If you add onload to the img, then the function will be called each time the image is loaded, which causes an infinite loop.
If you cannot modify the body tag, then replace your current function swapPic() with this:
(function swapPic() {
var imgSrc = [];
imgSrc[0] = "/Content/Resources/cafe1.jpg";
imgSrc[1] = "/Content/Resources/cafe2.jpg";
imgSrc[2] = "/Content/Resources/cafe3.jpg";
imgSrc[3] = "/Content/Resources/cafe4.jpg";
imgSrc[4] = "/Content/Resources/cafe5.jpg";
imgSrc[5] = "/Content/Resources/cafe6.jpg";
var randomnumber = Math.floor(Math.random() * 5);
var img = document.getElementById("imgContainer");
img.setAttribute("src", imgSrc[randomnumber]);
// alert("ok");
})();
This will execute it exactly once. No need to call it anywhere.
images have their own load event that refers to when the image finishes loading. so, each time you update the src, the browser of course starts loading the image, and fires the event again once it finishes loading it. the cycle repeats.
You could use window.onload to call your function just once, because the window's load event can only happen once.
You've attached onload to an image. In this case swapPic() will be called on every image load. So, what happens is an endless loop - you call swapPic(), it loads a new image which triggers again swapPic(). For more information look at W3Schools: Event - Img Onload.
You should move the swapPic() to body. This will trigger swapPic() only when the body is loaded.
Another way is to use javascript:
// if you have jQuery
$(document).ready(function(){
swapPic()
});
// ordinary javascript
window.onload = function() {
swapPic();
}
Use the onload function in tab. BTW according to your code your imgSrc[5] = "/Content/Resources/cafe6.jpg"; will never be shown as your random function only generates 0-4.
it should be
var randomnumber = Math.floor(Math.random() * 6);
I've built a modal image gallery. When the user clicks next to see next image I run something like:
document.getElementById('gallery-image').src = newSRC;
My problem is that there is a delay from when the user clicks next to where the image actually changes. (due to the new image being loaded). I want to "empty" the image element the moment the user clicks next. I tried doing this:
document.getElementById('gallery-image').src = '';
setTimeout(function(){
document.getElementById('gallery-image').src = newSRC;
}, 100);
to no avail.
How can I "empty" the IMG element until the new image starts loading on it?
There are three main ways to do this. Your question seemed to suggest you want to create an effect similar to a slide projector changing slides, so I have written this answer with that in mind.
Temporarily set the src property to a 1x1 transparent GIF instead of the empty string. This is most similar to what you tried to do and perhaps is the simplest method.
The data URI below is from Blank image encoded as data-uri and should work in Internet Explorer 8 or higher and the other major browsers. Using a data URI avoids the need to store a separate file on your web server and preload it when your page loads. You may need to set the width and height attributes of the img element to preserve the layout of your page.
This code does not preload the image at the start of the time delay (although it would be possible to do so), thus the apparent delay to the viewer is the sum of the programmed time delay and the time taken to load the image. The loading time will only be close to zero if the browser has already cached the image or if the web server is on the local network.
var gi = document.getElementById('gallery-image');
gi.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
setTimeout(function(){
document.getElementById('gallery-image').src = newSRC;
}, 100);
Temporarily set display: none;, and use an onload function to undo the change once the time delay has elapsed and the image has loaded. The code below starts loading the image at the start of the time delay, which depending on the viewer's connection speed, may result in a more consistent apparent delay.
var gi = document.getElementById('gallery-image');
var delayElapsed = false;
var imageLoaded = false;
gi.style.display = 'none';
setTimeout(function(){
delayElapsed = true;
maybeShowImage();
}, 100);
gi.onload = function() {
imageLoaded = true;
maybeShowImage();
};
gi.src = newSRC;
function maybeShowImage() {
if (!delayElapsed || !imageLoaded) {
return;
}
gi.style.display = '';
}
Do the above, but set visibility: hidden; instead. This may have the advantage of not affecting the page layout where display: none; would.
// [...]
gi.style.visibility = 'hidden';
// [...]
function maybeShowImage() {
if (!delayElapsed || !imageLoaded) {
return;
}
gi.style.visibility = '';
}
You could hide the image and then reshow it...
// Hide
document.getElementById('gallery-image').style.display = "none";
// Show
document.getElementById('gallery-image').style.display = "";
I want to load html , and then get the true image height.
$("#cover").html(stuff); //this has the image inside it
$(function(){
console.log($("#cover img").height()); //sometimes it's 0
});
For some reason, height is sometimes 0. Could it be because the image hasn't been fully loaded yet, and JQuery sees it as 0? If so, how do I overcome this? Is there a callback or something when the image is loaded?
You can use the .load() method of jQuery
$('#cover').html(stuff);
$('#cover img').load(function () {
console.log($(this).height());
};
Why do the console.log inside an anonymous function? Have you tried this?
$("#cover").html(stuff); //this has the image inside it
console.log($("#cover img").height());
//locate the image(s)
$("#cover img").each(function(){
//Build a new Image Object outside the DOM
//that way, CSS won't affect it
var img = new Image();
//add a callback when loaded
img.onload = function(){
//your width and height
//img.width
//img.height
}
//use the image src to load
//use attr() to resolve path issues across browsers
img.src = $(this).attr('src');
});
try to using load method method that we can take advantage of to make this work the way we want it too.
The problem we have right now is that, in the Webkit browsers, the jQuery code runs when the DOM is ready and the DOM is ready before the image has been loaded. So the code runs but since there’s no image to get a width of, we get 0 for the image’s width. We can use the load method to make the code wait until the window has loaded entirely before it runs.
$(window).load(function() {
console.log($("#cover img").height());
});
try using attr() to get the height:-
$("#yourElemengtID").attr('height')
Here is a piece of small code i used before hope this will help you
On my displayed image when mouse is in call this function
function MouseIn()
{
var src;
//to get original image size
var img =$(this);// displayed image
var theImage = new Image();// create a cache image
var imgsource =img.attr("src");// take the src of displayed image
theImage.src = imgsource;// give cached image the source of displayed image
var original_height = theImage.height// take height of image from the source
var original_width = theImage.width;//take width of image from the source
// to get the displayed image size
var Image_displaysize_width= img.width();
var Image_displaysize_height= img.height();
}
Don't you mean to do something like this?
jQuery("#myImg")[0].naturalHeight
better still don't use overhead of jQuery when possible.
document.getElementById('myImg').naturalHeight