Change backgroundImage with javascript for image slideshow. - javascript

I'm trying to change the background image of a div depending on it's id and then make a slideshow with a couple of images. I'm able to change the background with javascript but have a hard time figuring out why my loop doesn't work.
main.js
var spotlight = document.getElementById('spotlight');
var pics = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var totalPics = pics.length;
var i = 0;
function loop() {
if(i > (totalPics - 1)) {
i = 0;
}
spotlight.style.backgroundImage="url(/images/posts/'+pics[i]+')";
i++;
loopTimer = setTimeout('loop()',1000);
}
loop();
I'm using sass, but as javascript is client side this shouldn't work any different I guess? What am I doing wrong in my loop?
I have followed the basic principles found on w3Schools of changing the style with javascript and it works with a static image so my guess is that I have done something wrong in the loop.
Thanks

Change this:
spotlight.style.backgroundImage="url(/images/posts/" + pics[i]+ ")";
and
loopTimer = setTimeout(loop,1000);
See, if that helps.

Try changing your setTimeout to the following
loopTimer = setTimeout('loop', 1000);

Related

How can we make Image Carousel with background Image Property

I'm making an image carousel i'm bounded to use background-image property instead of using
<img src="Image">
tag. my carousel is working if I use img tag . But its not working when I use background-image property, how can I modify my code with background-image property.
see my fiddle :https://jsfiddle.net/korLasen/ and update it please thanks :)
or you can see code here
(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
function imageSliderSet(){
image.setAttribute('data-background', imageSet[index]);
index++;
if(index >= imageSet.length){
index = 0;
}
}
setInterval = (imageSliderSet, 2000);
})();
This is quite a strange question... however, I am not one to judge :)
Here is a jsfiddle based on your example. I ended up using jquery for this. I hope this is somewhere near what you were looking for!
This is based on changing every two seconds. To extend that, you can change line 18 in the jquery. Here is the jquery:
$( document ).ready(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
window.setInterval(function(){
image.css('background-image', "url('" + imageSet[index] + "')");
index++;
if(index >= imageSet.length){
index = 0;
}
//here you can adjust the time interval for each photo
}, 2000);
});

Creating a very simple game in JS

I'm currently making a game in JS, and I faced a problem.
I got an 2D array that stores an image, now I want some random pic to be changed every 1 second, everything is working but, I don't know how I can change the picture.
Do I have to print all the other images if I want to change the random cell in the array?
I'm almost sure that there's another way to change it without doing it.
I'll be glad for help, if anyone needs other explanation I'll be glad to.
You can try using something like this in your header. It should call changePic() every second, incrementing through your picture array, and setting the new picture on an image element.
//know your array sizes
var max_x = picArr.length;
var max_y = picArr[0].length;
var current_x = 0;
var current_y = 0;
function changePic()
{
if(current_y == max_y-1)
{
if(current_x == max_x-1)
{
current_x = 0;
current_y = 0;
}
else
{
current_x++;
current_y = 0;
}
}
else
current_y++;
var pic = picArr[current_x][current_y];
getElementById('randomImage').setAttribute('src', pic);
window.setTimeout(changePic, 1000);
}
setTimeout(changePic, 1000);
https://developer.mozilla.org/en/DOM/window.setTimeout
I would start out with something like
var ImageOne = new Image();
ImageOne.src = "UrlToImage";
And so on just to make sure all the images are loaded when the game starts
Thereafter I would be using jQuery:
$("#IdOfImg").attr("src", ImageOne);
You might want to try using a css class for the elements with a background image rather dan adding images to the DOM. I think a css class for back.png and one for the 1.png should do the trick.
Toggle the classes on the td elements every second.
Hope this helps.

custom background fadeInOut gallery

Because of this background image's fadeInOut transitions produces weird effect in white all the texts i decided to program my own custom image rotator with fadeinout effect
var intervalo;
var i= 0;
var photos = [
"http://toniweb.us/gm/img/galeria/fondo1.jpg",
"http://toniweb.us/gm/img/galeria/fondo2.jpg",
"http://toniweb.us/gm/img/galeria/fondo3.jpg",
"http://toniweb.us/gm/img/galeria/fondo4.jpg"
];
function rotarFondo(){
var container = $('#headerimgs');
var current = container.children('div:visible:first');
var imgSrc = photos[i];
i++;
if(i == photos.length)
i = 0;
console.log(imgSrc);
var next = (current.next().length > 1) ? current.next() : container.children('div:visible');
current.css('background',imgSrc);
next.css('background',imgSrc);
current.fadeOut(300);
next.fadeIn(300);
}
function congelarFondo(){
}
$(document).ready(function(){
if (intervalo )
clearInterval(intervalo );
intervalo = setInterval('rotarFondo()',1000);
});
the interval thing and the image calculation seems to work fine, but i don't know why the bgImgaes are actually not being applied,
Testing here for now http://jsfiddle.net/bE9Dq/27/
any idea??
Well for starters it might save you some time and a few headaches to use one of these plugins:
http://buildinternet.com/project/supersized/
http://bavotasan.com/2011/full-sizebackground-image-jquery-plugin/
(I've used them both)
First thing I've noticed with your code is you may need to set the background image as follows:
.css('background-image','url(' + imgSrc + ')');
Also notice on the second line ( the next.) you are still using imgSrc I think you mean to use imgSrc1 instead?

How to improve image cross-fade performance?

I want to be able to do a cross fade transition on large images whose width is set to 100% of the screen. I have a working example of what I want to accomplish. However, when I test it out on various browsers and various computers I don't get a buttery-smooth transition everywhere.
See demo on jsFiddle: http://jsfiddle.net/vrD2C/
See on Amazon S3: http://imagefader.s3.amazonaws.com/index.htm
I want to know how to improve the performance. Here's the function that actually does the image swap:
function swapImage(oldImg, newImg) {
newImg.css({
"display": "block",
"z-index": 2,
"opacity": 0
})
.removeClass("shadow")
.animate({ "opacity": 1 }, 500, function () {
if (oldImg) {
oldImg.hide();
}
newImg.addClass("shadow").css("z-index", 1);
});
}
Is using jQuery animate() to change the opacity a bad way to go?
You might want to look into CSS3 Transitions, as the browser might be able to optimize that better than Javascript directly setting the attributes in a loop. This seems to be a pretty good start for it:
http://robertnyman.com/2010/04/27/using-css3-transitions-to-create-rich-effects/
I'm not sure if this will help optimize your performance as I am currently using IE9 on an amped up machine and even if I put the browser into IE7 or 8 document mode, the JavaScript doesn't falter with your current code. However, you might consider making the following optimizations to the code.
Unclutter the contents of the main photo stage by placing all your photos in a hidden container you could give an id of "queue" or something similar, making the DOM do the work of storing and ordering the images you are not currently displaying for you. This will also leave the browser only working with two visible images at any given time, giving it less to consider as far as stacking context, positioning, and so on.
Rewrite the code to use an event trigger and bind the fade-in handling to the event, calling the first image in the queue's event once the current transition is complete. I find this method is more well-behaved for cycling animation than some timeout-managed scripts. An example of how to do this follows:
// Bind a custom event to each image called "transition"
$("#queue img").bind("transition", function() {
$(this)
// Hide the image
.hide()
// Move it to the visible stage
.appendTo("#photos")
// Delay the upcoming animation by the desired value
.delay(2500)
// Slowly fade the image in
.fadeIn("slow", function() {
// Animation callback
$(this)
// Add a shadow class to this image
.addClass("shadow")
// Select the replaced image
.siblings("img")
// Remove its shadow class
.removeClass("shadow")
// Move it to the back of the image queue container
.appendTo("#queue");
// Trigger the transition event on the next image in the queue
$("#queue img:first").trigger("transition");
});
}).first().addClass("shadow").trigger("transition"); // Fire the initial event
Try this working demo in your problem browsers and let me know if the performance is still poor.
I had the same problem too. I just preloaded my images and the transitions became smooth again.
The point is that IE is not W3C compliant, but +1 with ctcherry as using css is the most efficient way for smooth transitions.
Then there are the javascript coded solutions, either using js straight (but need some efforts are needed to comply with W3C Vs browsers), or using libs like JQuery or Mootools.
Here is a good javascript coded example (See demo online) compliant to your needs :
var Fondu = function(classe_img){
this.classe_img = classe_img;
this.courant = 0;
this.coeff = 100;
this.collection = this.getImages();
this.collection[0].style.zIndex = 100;
this.total = this.collection.length - 1;
this.encours = false;
}
Fondu.prototype.getImages = function(){
var tmp = [];
if(document.getElementsByClassName){
tmp = document.getElementsByClassName(this.classe_img);
}
else{
var i=0;
while(document.getElementsByTagName('*')[i]){
if(document.getElementsByTagName('*')[i].className.indexOf(this.classe_img) > -1){
tmp.push(document.getElementsByTagName('*')[i]);
}
i++;
}
}
var j=tmp.length;
while(j--){
if(tmp[j].filters){
tmp[j].style.width = tmp[j].style.width || tmp[j].offsetWidth+'px';
tmp[j].style.filter = 'alpha(opacity=100)';
tmp[j].opaque = tmp[j].filters[0];
this.coeff = 1;
}
else{
tmp[j].opaque = tmp[j].style;
}
}
return tmp;
}
Fondu.prototype.change = function(sens){
if(this.encours){
return false;
}
var prevObj = this.collection[this.courant];
this.encours = true;
if(sens){
this.courant++;
if(this.courant>this.total){
this.courant = 0;
}
}
else{
this.courant--;
if(this.courant<0){
this.courant = this.total;
}
}
var nextObj = this.collection[this.courant];
nextObj.style.zIndex = 50;
var tmpOp = 100;
var that = this;
var timer = setInterval(function(){
if(tmpOp<0){
clearInterval(timer);
timer = null;
prevObj.opaque.opacity = 0;
nextObj.style.zIndex = 100;
prevObj.style.zIndex = 0;
prevObj.opaque.opacity = 100 / that.coeff;
that.encours = false;
}
else{
prevObj.opaque.opacity = tmpOp / that.coeff;
tmpOp -= 5;
}
}, 25);
}

Dynamically changing images in a div

I've five images and would like to display it in a same div one by one with interval of 2 sec. Can anyone please suggest any solution for this?
Simple javascript example:
var currentImage = 0;
var images = [
'a.jpg',
'b.jpg'
];
var imageElement = document.getElementById('yourImageTagId');
function nextImage(){
currentImage = (currentImage + 1) % images.length;
imageElement.src = images[currentImage];
}
var timeoutId = setTimeout(nextImage, 1000);
It expects you to have some html like this:
<img src="a.jpg" id="yourImageTagId" />
Jquery Cycle is really flexible... you could hook it up to whatever youve got already marked up pretty easily.
There are many ways to do this nowadays but one simple way is using the following jquery plugin:
http://jquery.malsup.com/cycle/
Here is a simple demo in action fading images one after the other.
http://jquery.malsup.com/cycle/basic.html
setTimeout
You can do something like this.
function selectData(currentIndex) {
// select current's element "display" to "none" and show next element
...
// schedule next change in two second
setTimeout("selectData(" + nextIndex + ");", 2000);
};
I assume all images are inside that div already and have style display:none

Categories