Javascript Slide show - javascript

I have a simple fading slide-show which works great for a while, but runs to about 300 images. After a while it starts jumping and missing some, which I assume is down to too many images being loaded. Is there a way of 'unloading' images once viewed, or is it likely to be something else?

Let all images load before you display the slide show, or skip not loaded images.
You could do this like this for example:
var images = ['./path1.jpg', './path2.jpg']; // Array with all images
var imageCount, imagesLoaded, c;
imageCount = images.length; // Get images count
imagesLoaded = 0;
for (c = 0; c < imageCount ; c++){ // Loop thorough all images
var image = document.createElement('img'); // Create img tag
image.setAttribute('src', images[c]); // Set src attribute
document.body.appendChild(image); // Add img tag to body
image.onload = function() {
imagesLoaded++; // Add loaded image to loaded images count
console.log('Loaded: ' + imagesLoaded + '/' + imageCount); // debug
if (imagesLoaded == imageCount){ // when all images loaded
// Start your slideshow
}
}
}

Related

Thumb rotator by IMG URL folder location in jQuery

How to get folder location from IMG URL example https://cdn1.example.com/thumbs/23432/0.jpg via jQuery and to allow to set max images can be found on the folder example Total = 5 ( Images can be found in the folder URL).
The script after to generate the images URLs from the IMG URL example
https://cdn1.example.com/thumbs/23432/0.jpg
https://cdn1.example.com/thumbs/23432/1.jpg
https://cdn1.example.com/thumbs/23432/2.jpg
https://cdn1.example.com/thumbs/23432/3.jpg
https://cdn1.example.com/thumbs/23432/4.jpg
When a person hovers the "a link" with the mouse the image rotator to start with IMG 0.jpg ( First image from the list ) and END with 4.jpg
When the person remove the mouse from the a href to show the original image from <img src="(original link)" />.
I try some scripts but most of them need to add the links manually I was hoping I can find a script to work this way, and I see some issue with most thumb rotators, when they start to rotate some images is not fully loaded, I was hoping if there's a way to load images first before start rotate them.
HTML example:
<img src="https://cdn1.example.com/thumbs/23432/2.jpg" />
var hoverstatus = false;
var imgArr = ["https://picsum.photos/200/300", "https://picsum.photos/id/237/200/300", "https://picsum.photos/seed/picsum/200/300"];
function imagehover() {
hoverstatus = true;
for (var i = 0; i < imgArr.length; i++) {
var time = 1000 * (i + 1);
changeImage(i, time);
}
}
function changeImage(i, time) {
if (hoverstatus == false) {
imagehoverout();
return;
}
setTimeout(function() {
console.log(i);
jQuery('.video img').attr('src', imgArr[i]);
}, time);
}
function imagehoverout() {
hoverstatus = false;
$('.video img').attr('src', 'https://picsum.photos/200/300.jpg');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img onmouseover="imagehover()" onmouseout="imagehoverout()" src="https://picsum.photos/200/300.jpg" />

Multiple images not load on canvas

I have created Circle using arc like following way.
var startAngle = 0;
var arc = Math.PI / 6;
var ctx;
var leftValue=275;
var topValue=300;
var wheelImg = ["http://i.stack.imgur.com/wwXlF.png","http://i.stack.imgur.com/wwXlF.png","cat.png","cock.png",
"croco.png","dog.png","eagle.png","elephant.png","lion.png",
"monkey.png","rabbit.png","sheep.png"];
function drawWheelImg()
{
var canvas = document.getElementById("canvas");
if(canvas.getContext)
{
var outsideRadius = 260;
var textRadius = 217;
var insideRadius = 202;
ctx = canvas.getContext("2d");
for(var i = 0; i < 12; i++)
{
var angle = startAngle + i * arc;
ctx.beginPath();
ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
ctx.arc(leftValue, topValue, insideRadius, angle + arc, angle, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
ctx.shadowBlur=3;
ctx.shadowColor="#A47C15";
ctx.stroke();
ctx.closePath();
ctx.save();
ctx.translate(leftValue + Math.cos(angle + arc / 2) * textRadius,
topValue + Math.sin(angle + arc / 2) * textRadius);
ctx.rotate(angle + arc / 2 + Math.PI / 2);
var img = new Image();
img.src = wheelImg[i];
ctx.drawImage(img,-44, -25,50,40);
ctx.restore();
}
}
}
function spin()
{
drawWheelImg();
}
drawWheelImg();
<button class="btnSpin" onclick="spin();">Spin</button>
<canvas id="canvas" width="550" height="580"></canvas>
Problem is that it will not load when first page load. But when i click on spin button it will load all images.
Don't know what is the issue. Any help is greatly appreciated.
Note: Here in the question same issue is solve by img.onload function but that for only single image. If there is number of multiple images in array then it's not working.
You want to preload the images.
To do this you can start the loading at the bottom of the page just before the closing </dody> tag.
<script>
// an array of image URLs
var imageNames = ["image1.png", "image2.jpg", ...moreImageNames];
// an array of images
var images = [];
// for each image name create the image and put it into the images array
imageNames.forEach(function(name){
image = new Image(); // create image
image.src = name; // set the src
images.push(image); // push it onto the image array
});
</script>
In the code that uses the images you just need to check if they have loaded yet. To do this just check the image complete attribute.
// draw the first image in the array
if(images[0].complete){ // has it loaded
ctx.drawImage(images[0],0,0); // yes so draw it
}
Note that complete does not mean loaded. If you proved a bad URL or there is another error the complete flag will still be true. Complete means the browser has finished dealing with the image. You will have to add an onload event if there is a chance that images may fail.
Handling Errors
If you are unsure that an image will not load you will have to devise a strategy to deal with the missing content. You will need to answer questions like, Can my app function without the image? Are there alternative sources to get the image from? Is there a way to determine how often this is likely to happen? How do I stop this from happening?
On the simplest level you can flag an image as loaded by adding your own semaphore to the image object during the onload event
// an array of image URLs
var imageNames = ["image1.png", "image2.jpg", ...moreImageNames];
// an array of images
var images = [];
// function to flag image as loaded
function loaded(){
this.loaded = true;
}
// for each image name create the image and put it into the images array
imageNames.forEach(function(name){
image = new Image(); // create image
image.src = name; // set the src
image.onload = loaded; // add the image on load event
images.push(image); // push it onto the image array
});
Then in code you will check for the loaded semaphore before using the image.
// draw the first image in the array
if(images[0].loaded){ // has it loaded
ctx.drawImage(images[0],0,0); // yes so draw it
}
Critical content
If you have images that are required for you app to function then you should redirect to an error page if there is a problem loading the image. You may have several servers so you can also try the different sources before giving up.
If you need to stop the app or try an alternative URL you will have to intercept the onerror image event.
To simplify your use of the images (100% sure the images are loaded when that app runs) you should start the parts that use the images only when all the images are loaded. One way to do this is to count all the images that are being loaded, and count down as the images load. When the counter reaches zero you know all the images have loaded and you can then call you app.
The following will load images, if they fail it will try another server (source) until there are no more options at which point you should redirect to the appropriate error page to inform the client that a monkey has put a spanner in the works. It counts the loading images and when all the images have loaded then it will start the app running, sure in the knowledge that all the image content is safe to use.
// Server list in order of preferance
var servers = ["https://fakesiteABC.com/", "http://boogusplace.com/", "http://foobarpoo.com.au/"];
// an array of image URLs
var imageNames = ["image1.png", "image2.jpg", ...moreImageNames];
// an array of images
var images = [];
// loading count tracks the number of images that are being loaded
var loadingImageCount = 0;
// function to track loaded images
function loaded(){
loadingImageCount -= 1;
if(loadingImageCount === 0){
// call your application start all images have loaded
appStart();
}
}
// function to deal with error
function loadError(){ // the keyword "this" references the image that generated the event.
if(this.retry === undefined){ // is this the first error
this.retry = 1; // point to the second server
}else{
this.retry += 1; // on each error keep trying servers (locations)
}
// are the any other sources to try?
if(this.retry >= servers.length){ // no 11
// redirect to error page.
return;
}
// try a new server by setting the source and stripping the
// last server name from the previous src URL
this.src = servers[this.retry] + this.src.replace( servers[ this.retry - 1],"");
// now wait for load or error
}
// for each image name create the image and put it into the images array
imageNames.forEach(function(name){
image = new Image(); // create image
image.src = servers[0] + name; // set the src from the first server
image.onload = loaded; // add the image on load event
image.onerror = loadError; // add the image error handler
images.push(image); // push it onto the image array
loadingImageCount += 1; // count the images being loaded.
});
There are many other strategies for dealing with missing content. This just shows some of the mechanism used and does not define a perfect solution (there is none)

Pre-loading images with Javascript | Not Working

I have a masonry grid where the images are black and white and when you hover over them, the color images appear. They are not composite images. They are all separate. (I'm just sorting out bugs for someone else's code)
On initial hover after a fresh page load, there is a delay (and grey overlay) when hovering over. After the initial, it's of course instantaneous when it switches to the color photo.
So what I'm trying to do is pre load the images with some javascript, but I'm having trouble doing this. Below is what I have for code. Also, this is in Wordpress. Not sure if that matters.
All of the images are background images too, not hardcoded into the html. It's all background css. Thanks for any help!
<script language="JavaScript">
$('document').ready(function preloader() {
// counter
var i = 0;
// create object
imageObj = new Image();
// set image list
images = new Array();
images[0]="images/treatment_locations.jpg"
images[1]="images/community_news_events.jpg"
images[2]="images/success_stories.jpg"
images[3]="images/self_assessment.jpg"
images[4]="images/our_associates.jpg"
images[5]="images/treatment_programs.jpg"
images[6]="images/patient_portal.jpg"
images[7]="images/FAQ.jpg"
images[8]="images/what_to_expect.jpg"
// start preloading
for(i=0; i<=8; i++)
{
imageObj.src=images[i];
}
});
</script>
If you overwrite the src in each iteration, you're not giving the browser a chance to fetch the image. You probably only preload the last image.
Try:
var imageObjs = [];
$('document').ready(function preloader() {
// counter
var i = 0;
// set image list
images = new Array();
images[0]="images/treatment_locations.jpg"
images[1]="images/community_news_events.jpg"
images[2]="images/success_stories.jpg"
images[3]="images/self_assessment.jpg"
images[4]="images/our_associates.jpg"
images[5]="images/treatment_programs.jpg"
images[6]="images/patient_portal.jpg"
images[7]="images/FAQ.jpg"
images[8]="images/what_to_expect.jpg"
// start preloading
for(i=0; i<=8; i++)
{
var imageObj = new Image();
imageObj.src=images[i];
imageObjs.push(imageObj);
}
});
That's another aproach, where it stores only the images that were successfully loaded.
var imgObjs = [];
$(document).ready(function preloader() {
// images list
var images = [
'treatment_locations.jpg',
'community_news_events.jpg',
'success_stories.jpg',
'self_assessment.jpg',
'our_associates.jpg',
'treatment_programs.jpg',
'patient_portal.jpg',
'FAQ.jpg',
'what_to_expect.jpg'
];
for (var i in images) {
var img = new Image();
img.src = 'images/' + images[i];
// stores it on array after loading
img.onload = function() {
imgObjs.push(this);
};
}
});

Prev & Next button with counter for overlay using jQuery

I build this image gallery using jquerytools, I'm using scrollable div on thumbs and overlay on the main image... Everything works like charm..
EDIT: Before I make this a bounty...I have to explain that I need something clean and simple like this, because the images come from php (encrypted) , and I can't modify this, just the "view" as I need to achieve this with something like classes and ids. This is why I try this but...
The problem is I need to insert a Next and Prev Buttons when you are viewing the overlay... so you can go trough the images, once the overlay has been loaded..
I have made this fiddle for you my teachers full of wisdom can see what I am saying. http://jsfiddle.net/s6TGs/5/
I have really tried. but api.next() it's working for the scrolling on the thumbs , so I don't know how can I tell this script.. hey if next is clicked, yo pls insert next url on thubs, if previous btn is clicked, pls go to prev url on thumbs.. But I can't
Also and no less important a Counter like 1/8 have to be displayed =S... how in the name of JavaScript you do this..
Here is My code
$(function() {
$(".scrollable").scrollable();
$(".items img").click(function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap2.find("img").attr("src", url);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").click();
});
// This makes the image Overlay with a div and html
$(document).ready(function() {
$("img[rel]").overlay({
// some mask tweaks suitable for modal dialogs
mask: {
color: '#ebecff',
loadSpeed: 200,
opacity: 0.9
},
closeOnClick: true
});
});
I know here is part of my answer I just can make it work :(
http://jquerytools.org/demos/combine/portfolio/index.html
EDIT: Thanks to the first answer by QuakeDK I almost achieve the goal.. But the counter is not ok, also when you get to the 4 image (number 5 on counter) you cant go to the 5th thumb .. This is the CODE with that answer integrated
http://jsfiddle.net/xHL35/5/
And here is the CODE for PREV & NEXT BUTTON
//NExt BTN
$(".nextImg").click(function(){
// Count all images
var count = $(".items img").length;
var next = $(".items").find(".active").next("img");
if(next.is(":last")){
next = $(".items").find(".active").parent().next("div").find("img:first");
if(next.index() == -1){
// We have reached the end - start over.
next = $(".items img:first");
scrollapi.begin(200);
} else {
scrollapi.next(200);
}
}
// Get the current image number
var current = (next.index("img"));
var nextUrl = next.attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", nextUrl);
wrap2.find("img").attr("src", nextUrl);
};
// begin loading the image from www.flickr.com
img.src = nextUrl;
$("#imageCounter").html("Image: "+current+" of "+count);
// activate item
$(".items img").removeClass("active");
next.addClass("active");
});
//PREV BTN
$(".prevImg").click(function(){
// Count all images
var count = $(".items img").length;
var prev = $(".items").find(".active").prev("img");
if(prev.is(":first")){
prev = $(".items").find(".active").parent().prev("div").find("img:first");
if(prev.index() == -1){
// We have reached the end - start over.
prev = $(".items img:first");
scrollapi.begin(200);
} else {
scrollapi.prev(200);
}
}
// Get the current image number
var current = (prev.index("img"));
var prevUrl = prev.attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", prevUrl);
wrap2.find("img").attr("src", prevUrl);
};
// begin loading the image from www.flickr.com
img.src = prevUrl;
$("#imageCounter").html("Image: "+current+" of "+count);
// activate item
$(".items img").removeClass("active");
prev.addClass("active");
});
There must be a reward option here, if somebody help me I give you 20box! jajaja I'm desperate. Because now I also need to display title for each image, and I think it's the same process of URL replace, but next & prev is just something I can't manage.. Post the full solution and your email on paypal, I will pay 20!
Okay, never tried jQueryTOOLS, so thought it would be fun to play with.
first of all, here's the JSFiddle I just created: http://jsfiddle.net/xHL35/1/
Now, the API calls need a variable to hold it
$(".scrollable").scrollable();
var scrollapi = $(".scrollable").data("scrollable");
Now scrollapi, can call the functions like this:
scrollapi.next(200);
I've copied your own code for choosing image and just rewritten it to fit the NEXT image.
I haven't created the PREV function, but should not be that hard to reverse the NEXT function.
$(".nextImg").click(function(){
// Count all images
var count = $(".items img").length;
// Finding the next image
var next = $(".items").find(".active").next("img");
// Is the next image, the last image in the wrapper?
if(next.is(":last")){
// If it is, go to next DIV and get the first image
next = $(".items").find(".active").parent().next("div").find("img:first");
// If this dosn't exists, we've reached the end
if(next.index() == -1){
// We have reached the end - start over.
next = $(".items img:first");
scrollapi.begin(200);
} else {
// Not at the end, show next div in thumbs
scrollapi.next(200);
}
}
// Get the current image number
var current = (next.index("img"));
var nextUrl = next.attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", nextUrl);
wrap2.find("img").attr("src", nextUrl);
};
// begin loading the image from www.flickr.com
img.src = nextUrl;
// Show the counter
$("#imageCounter").html("Image: "+current+" of "+count);
// activate item
$(".items img").removeClass("active");
next.addClass("active");
});
Hoping you can use this to develop the rest of the gallery.

using onmouseover as

I have a continuous loop of alternating images that I would like to be able to interrupt and have display a new picture that corresponds with the current displayed picture using an onmouseover affect for as long as the mouse is on the image.
As an example to better describe my problem, I would like to have a bunch of images alternating on the screen every five seconds (which I can already do). Then when the mouseover event happens, have the images stop alternating and have a new image displayed that corresponds with the image that was just displayed (it will be another image that describes the image that was just being displayed). I also want the images to stop alternating while the mouse is over the images.
So far I can get the first image to display its corresponding image, but I can't seem to get the rest to work. Also I can't get the alternating images to stop while the mouse is still on the image.
Here's what I have so far:
<body>
<img src="image1.jpeg" alt="Image1" width="344" height="311" id="rotator" onmouseover="this.src='imageText1.jpeg'" onmouseout="this.src='image1.jpeg'">
<script type="text/javascript">
(function() {
var rotator = document.getElementById("rotator");
var imageDir = '';
var delayInSeconds = 5;
var images = ["image2.png", "image3.gif", "image4.png", "image5.jpeg","image6.gif", "image7.jpeg", "image1.jpeg"];
var num = 0;
if (rotator.onmouseover == )
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
if (rotator.onmouseover == )
{
}
we must check something in if conditon.
empty condition is a problem.please check it.

Categories

Resources