I am using setInterval for change image on mouse over, I want that set interval call again after or next interval comes after only when image loaded..
Following is my code:
jQuery('.product').on('mouseover',function(){
timer = setInterval(function() {
if (counter !== 0) {
time = 2000;
}
if (counter === product_images.length) {
counter = 0;
}
selector.attr('src', 'localhost/product/' + product_images[counter]);
var loadImage = new Image();
loadImage.src = selector.attr('src');
loadImage.onload = function(){
selector.show();
};
counter = counter + 1;
},1000);
});
What i want that before coming next image using set interval time next image should not be loaded until previous one not loaded... and in that time i want display loading image
How could i do it with jquery promise or by other solution.
Please help me...
One more thing i do not want to called next interval until first image not loaded
you can use document.ready
call the function inside document.ready so once the page is completely loaded your function will be called
first Load the images when page is loading in header,then those image will be in browser cache then it works fine,
Just Try this :
if (document.images) {
img1 = new Image();
img1.src = "imgpath/image1.png";
img2 = new Image();
img2.src = "imgpath/image2.png"";
}
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';
}
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
}
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 working on making a JS script that will go in the header div and display a few pictures. I looked into JQuery Cycle, but it was out of my league. The code I wrote below freezes the browser, should I be using the for loop with the timer var?
<script type="text/JavaScript" language="JavaScript">
var timer;
for (timer = 0; timer < 11; timer++) {
if (timer = 0) {
document.write('<img src="images/one.png">');
}
if (timer = 5) {
document.write('<img src="images/two.png">');
}
if (timer = 10) {
document.write('<img src="images/three.png">');
}
}
</script>
Thanks!
Assuming you want a script to rotate images and not just write them to the page as your code will do, you can use something like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="target"></div>
<script>
var ary = ["images/one.png","images/two.png","images/three.png"];
var target = document.getElementById("target");
setInterval(function(){
target.innerHTML = "<img src=\""+ary[0]+"\" />";
ary.push(ary.shift());
},2000);
</script>
</body>
</html>
Of course the above code has no effects (like fading) which jQuery will give yous, but it also doesn't require loading the entire jQuery library for something so basic.
How about just running the script after the page loads?
<script>
// in <head> //
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
}
</script>
Then use <body onload="load();"> to run the script.
Edit
To add in a delay loading images, I rewrote the code:
<script>
// in <head> //
var displayOnLoad = true; // Set to true to load the first image when the script runs, otherwise set to false to delay before loading the first image
var delay = 2.5; // seconds to delay between loading images
function loadImage(url) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
setTimeout(loadImage(images[i]), (i+displayOnLoad)*(delay*1000));
}
}
</script>
Set displayOnLoad = false; if you want to wait the specified delay before loading the first image. The delay is set in seconds. I recommend waiting over a single second between images, as they may take some time to download (depending on the user's internet speed).
As with the first snippet, I haven't tested the code, so please tell me if an error occurs, and I will take a look.
Since you used the jquery tag on your question, I assume you are OK with using jQuery. In which case, you can do something like this:
In your static HTML, include the img tag and set its id to something (in my example, it's set to myImg) and set its src attribute to the first image, e.g.:
<img id="myImg" src="images/one.png">
Next, use jQuery to delay execution of your script until the page has finished loading, then use setTimeout to create a further delay so that the user can actually spend a few seconds looking at the image before it changes:
<script>
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
$(function() {
// Document is ready
setTimeout(function() {
// We will get here after the first timer expires.
// Change the image src property of the existing img element.
$("#myImg").prop("src", "images/two.png");
setTimeout(function() {
// We will get here after the second, nested, timer expires.
// Again, change the image src property of the existing img element.
$("#myImg").prop("src", "images/three.png");
}, imgTimeoutMsecs);
}, imgTimeoutMsecs);
});
</script>
Of course, that approach doesn't scale very well, so if you are using more than three images total, you want to modify the approach to something like this:
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
// Array of img src attributes.
var images = [
"images/one.png",
"images/two.png",
"images/three.png",
"images/four.png",
"images/five.png",
];
// Index into images array.
var iCurrentImage = 0;
function cycleImage() {
// Increment to the next image, or wrap around.
if (iCurrentImage >= images.length) {
iCurrentImage = 0;
}
else {
iCurrentImage += 1;
}
$("#myImg").prop("src", images[iCurrentImage]);
// Reset the timer.
setTimeout(cycleImages, imgTimeoutMsecs);
}
$(function() {
// Document is ready.
// Cycle images for as long as the page is loaded.
setTimeout(cycleImages, imgTimeoutMsecs);
});
There are many improvements that can be made to that example. For instance, you could slightly simplify this code by using setInterval instead of setTimer.
The code you've provided simply iterates through the for loop, writing the images to the browser as it does so. I suggest you take a look at JavaScript setTimeout function.
JS Timing
I have set of images named as img1, img2, img3, img4,......., imgx. So, I want to code a JavaScript to display an image img1 at document.onload() and on first click image to be changed to img2 next on second click the image to be changed at img3 and then same to the next image on every NEXT button click. In this manner I need even PREVIOUS button to go back to the previously viewed images.
How to implement this?
var currentImage = 1;
window.onload = function() {
showImage();
};
document.getElementById("next").onclick = function() {
currentImage++;
showImage();
}
function showImage() {
document.getElementById("image").src = "img" + currentImage + ".jpg";
}
These are the basics and should help you get started. If you need help implementing the rest, ask us what you want to do specificially and what you tried. Hint, you'll need to handle the case where there is no "next" image to show. Do you want it to come back to the beggining or just not work?
<script type="text/javascript">
var images = new Array("img/image1.jpg", "img/image2.jpg", "img/image3.jpg");
var cur_image = 0;
function goNextImage() {
var img = document.getElementById('image');
cur_image++;
if (cur_image == images.length) {
cur_image = 0;
}
img.src = images[cur_image];
}
</script>
<img src="img/image1.jpg" id="image" onclick="goNextImage()" />