Hello I want to fadeOut image, and then do fadeIn with a new one, so I wrote a simple code, but something goes wrong, because when .photo img fadesOut, then fadesIn this same photo, but after, a few second its changes because of new "src", but even if browser didn't load a new image, the old one shound't show, becuase src is changed, but it shows, and after a second, maybe two changes to the new one. Can somebody tell me what's wrong?
var dimage = $next.children("img").attr("rel");
$(".photo img").fadeOut("slow", function () {
$(".photo img").attr("src", dimage);
$(".photo img").fadeIn("slow");
});
This may be because the image has to load after the src is altered.
Consider putting the image in a tag, then setting the css property to display:none. This way the image will preload in the browser before your script runs and will be available when it does.
you aren't giving the new image enough time to load.
function loadImage (src) {
return $.Deferred(function(def){
var img = new Image();
img.onload = function(){
def.resolve(src);
}
img.src = src;
}).promise();
}
var dimage = $next.children("img").attr("rel");
var imageLoadedDef = loadImage(dimage);
$(".photo img").fadeOut("slow", function () {
def.done(function(src){
$(".photo img").attr("src", src);
$(".photo img").fadeIn("slow");
});
});
the problem as highlighted is about images not ready for display when you call them, so the solution is to preload them before starting the slideshow, create a function with an array of images path
function preLoad(){
var imgs = {'test1.jpg', 'test2.jpg', 'test3.jpg'};
var img = document.createElement('img');
for(var i = 0; i < imgs.leght; i++){
img.src = imgs[i]; //all images gets preloaded at this stage
}
startSlider(); //here you will do your code
}
Related
I have an HTML button with an onclick function "clicked()".
If clicked I want to load an image as "background-image" of a div tag.
The image shall be loaded from a server that serves the image very unreliable (rain-radar),
very high answer time up to timeout. I have no control of the server but I am allowed
to fetch the image.
If the image cannot be loaded or is not loaded after 30 seconds I want to show either a failover image or a simple text message to try again later.
I tried to define a second (failover) image url to the style background-image attribute but
then my page always loads the failover image and I guess that's not how it works. Also I dont want to show a "loading image failed" image while page still waits to receive an answer...
index.html
...
GoToDiv
...
javascript:
function clicked(){
document.getElementById('gotoDiv').style.backgroundImage = "url('https://UNRELIABLE.SERVER/pic.jpg'), url('/failover.jpg')";
}
I there a proper way to do that?
You can try a preloading technique
function clicked() {
var elem = document.getElementById('gotoDiv');
elem.style.backgroundImage = 'url("loading.gif")';
function setErrorImg () {
elem.style.backgroundImage = 'url("failover.jpg")';
}
var timer = window.setTimeout(setErrorImg, 30000);
var img = new Image();
img.onload = function() {
window.clearTimeout(timer);
elem.style.backgroundImage = 'url("' + img.src + '")';
};
img.onerror = setErrorImg;
img.src = 'https://UNRELIABLE.SERVER/pic.jpg';
}
Is it possible to restart a gif animation without downloading the file every time?
My current code looks like this:
var img = new Image();
img.src = 'imgages/src/myImage.gif';
$('#id').css('background-image', 'url("' + img.src + '?x=' + Date.now() + '")' );
Edit
When I insert the gif into the dom it didn't restart the gif animation. I can only achieve this by appending a random string to the image src but this will download the image again.
I want to know if it is possible to restart the gif animation without downloading the gif.
I've had similar requirement.
var img = document.createElement("img"),
imageUrl = "http://i73.photobucket.com/albums/i231/charma13/love240.gif";
img.src = imageUrl;
document.body.appendChild(img);
window.restartAnim = function () {
img.src = "";
img.src = imageUrl;
}
for example on facebook - animated emoticons are not .gifs but a set of static frames on png file with dynamically set background offset. This way you have full control over your animation from javascript - you can even pause/unpause it or change its speed.
It's possible to split your .gif file into separate frames and generate a .png file on server side dynamically.
This looks like a good weekend project for me ;)
restartGif(imgElement){
let element = document.getElementById(imgElement);
if (element) {
var imgSrc = element.src;
element.src = imgSrc;
}
}
// Example:
restartGif("gif_box")
function refreshgif() {
var giffile = $(".gif-class");
giffile.src = giffile.src;
}
I had a similar problem and I solved it by adjusting the image's display attribute before restarting the gif. Also, set the timeout to make sure that the restarting the gif will run after the image attribute is changed.
const img = document.getElementById("gif");
img.style = "display: none;";
img.style = "display: block;";
setTimeout(() => {
img.src = img.src;
}, 0);
This is inspired by this answer.
Just make it loop forever? otherwise you could use an ajax request every (duration of gif) to restart it.
even with javascript it would be possible;
var gif
window.onload=function () {
gif=document.getElementById('id')
setInterval(function () {
gif.src=gif.src.replace(/\?.*/,function () {
return '?'+new Date()
})
},5000)//duration of your gif
}
This may help you,
var img = new Image();
src = 'imgages/src/myImage.gif';
img.src=src;
$('body').append(img);
setInterval(function(){
t=new Date().getTime();
$("img").attr("src", src+'?'+t);
},5000);
create a function in javascript and then reput the image in the same place. when you want to replay the Gif call this function.
function replayGif(){
var img = new Image();
img.src = 'imgages/src/myImage.gif';
$('#id').css('background-image', 'url("' + img.src + '?x=' + Date.now() + '")' );
}
The simplest javascript solution:
Function:
function restartGif(ImageSelector){
var imgSrc=document.querySelector(ImageSelector).src;
document.querySelector(ImageSelector).src=imgSrc;
}
Call function:
restartGif(SELECTOR) // Example: restartGif('.homer')
Example: http://jsfiddle.net/nv3dkscr/
Try to set the src of the gif animation to itself or set it to an empty string followed by the original src again. ;)
I'm creating a big page with a lot of blocks containing big background images, so I thought the best thing would be to show a preloader and load images in the background and update the loader (image 4 of 20, ecc). My problem is: when the onload event fires my loader diasppears but I still see the image loading, this means it wasn't completely loaded. Why does this happen? any idea?
here's the page:
http://zhereicome.com/experiments/statics/myascensor/#1-1
Thanks in advance
nImages = $('.slide').length;
loadedImgs = 0;
var bgImages = ['img/bbb.png','img/bbb2.png','img/bbb3.png'];
$('.slide').each(function(i){
var curSlide = $(this);
var img = new Image();
img.src = bgImages[ i % 3 ];
img.onLoad = imageLoaded(img, curSlide);
})
function imageLoaded(img, curSlide){
curSlide.css('backgroundImage', 'url(' + img.src + ')');
loadedImgs++;
if(nImages == loadedImgs){
$('#container').css('visibility','visible');
$('#loader-cont').fadeOut(1000);
}
$('.loader-inner .title').text(loadedImgs / nImages);
}
You seem to have some trouble with window.onload and document.ready:
$(document).ready(function(){
// This will be executed when the DOM is ready.
});
$(window).load(function(){
// This will be executed when the whole document and all its
// referenced items (style sheets, scripts, images, etc.) are loaded.
});
But this has been asked before and answered much, much better: How can I create a "Please Wait, Loading..." animation using jQuery?
I am changing src for image dynamically and want to capture on load event for that image. Is there a way I can do it?
Several years ago, I discovered that the onload event was not reliable in some browsers (I don't remember which ones) when setting .src for the second time. As such, I settled for replacing the image object. I would create a new image object, set the onload handler, set the .src value and then when it loads, insert it into the page in place of the existing image.
When creating an image from scratch in javascript, you do this:
var img = new Image();
img.onload = function() {
// put your onload code here
};
img.src = "xxx.jpg"
If you just want to change the .src of an image, you just find the DOM object in the page and set it's .src property.
var img = document.getElementById("myImage");
img.src = "xxx.jpg";
If you want to try to capture the onload event when resetting the .src (what I had reliability problems with a couple years ago, you would do this:
var img = document.getElementById("myImage");
img.onload = function() {
// your code here
};
img.src = "xxx.jpg";
If you want to load a new image and replace an existing one with it when it loads, you would do this:
function replaceImg(oldImage, newSrc) {
var img = new Image();
img.onload = function() {
var parent = oldImage.parentNode;
parent.insertBefore(img, oldImage);
parent.removeChild(oldImage);
// put any other code you want here when the
// replacement image is loaded and in place
};
img.src = newSrc;
}
And, you would call this like this:
<img id="myImage" src="yyy.jpg">
var oldImage = document.getElementById("myImage");
replaceImg(oldImage, "xxx.jpg");
// create image object
var image = new Image();
image.onload = function () {
// do stuff
$('#myimageelementid').prop('src', image.src); // set the element in the DOM with this image
}
image.src = "image.jpg"; // will trigger onload when loaded
It works in IE6, and FireFox; but for some reason not in IE7.
Using ASP.NET on the Page_Init I populate a list of chapters that are links to the image in the book as well as a Javascript array which holds the pageIDs.
ex.
Chapter 1 --> href="javascript:seePage(4);"
Here is the actual code I am using:
var availablePages = ['1002_001','1002_002','1002_003','1002_004','1002_005'];
function seePage(index) {
$get('imgSingle').src = 'graphics/loading.gif';
var img = new Image();
img.src = 'get.jpg.aspx?size=single&id=' + availablePages[index];
img.onload = function() {
var single = $get('imgSingle');
single.src = img.src;
}
}
When I click on Chapter 1, the image loads fine across the board (IE6,7,FF) and clicking on a second chapter link also works; however, in (and only in) IE7 does clicking on the same chapter twice (chap1, chap2, then chap1 again) does the image get stuck on the 'loading' image...
It's caused because IE will cache the image, and the onload event will never fire after it's already been loaded.
You need to position the onload event before the src.
var availablePages = ['1002_001','1002_002','1002_003','1002_004','1002_005'];
function seePage(index) {
$get('imgSingle').src = 'graphics/loading.gif';
var img = new Image();
img.onload = function() {
var single = $get('imgSingle');
single.src = img.src;
}
img.src = 'get.jpg.aspx?size=single&id=' + availablePages[index];
}
Another way of doing this is to check if the image is already loaded with image.complete. For instance:
var img = new Image();
img.src = 'foo.jpg';
if(img.complete){
img.onload = function(){ /* ... */ };
} else {
/* execute something else, or the same. */
}
I've experienced this behavior in IE6 and 7.