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);
});
Related
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);
I want my div element to work like a timer and shows random numbers with an interval of 1s. http://jsfiddle.net/NHAvS/46/. That is my code:
var arrData = [];
for (i=0;i<1000;i++)
{
arrData.push({"bandwidth":Math.floor(Math.random() * 100)});
}
var div = document.getElementById('wrapper').innerHTML =arrData;
document.getElementById('wrapper').style.left = '200px';
document.getElementById('wrapper').style.top = '100px';
but the problem is that it only shows 1 data at a time. any idea how to fix it?
Thanks
Do this:
setInterval(myfun,1000);
var div = document.getElementById('wrapper');
function myfun(){
div.innerHTML ='bandwidth :'+Math.floor(Math.random() * 100);
}
Take a Look: http://jsfiddle.net/techsin/NHAvS/49/
Note: your example was messed up as on left side it was set to load in head which means your div would be undefined every time your script loads before your dom. so setting it to onload make it works little more. :D
Note: also you seem to be chaining functions as in jquery, but in javascript you don't do that. The functions are made to do that. i.e. div= ..getElementById..innerHtml='balbla'; would set div = bla... not element.
You're better off using jQuery and CSS to achieve your desired result. jQuery to find the element and to display the random number; and CSS instead of manually setting the position. (Obviously jQuery is just a personal choice and document.getElementById will suffice - but if you're planning on manipulating the DOM a lot, jQuery is probably a better route to take). See updated fiddle
$(function () {
var arrData = [];
for (i = 0; i < 1000; i++) {
arrData.push({
"bandwidth": Math.floor(Math.random() * 100)
});
}
var index = 0;
setInterval(function(){
$("#wrapper").text(arrData[index].bandwidth);
index++;
}, 1000);
});
You can do it like this:
var delay = 1000, // 1000 ms = 1 sec
i;
setTimeout(function() {
document.getElementById('wrapper').innerHTML = arrData[i];
i++;
}, delay);
I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:
HTML
<div id="bg_left"></div>
<div id="bg_right"></div>
CSS
body{
height:100%;
}
#bg_left{
height:100%;
width:50%;
left:0;
position:fixed;
background-position:left;
}
#bg_right{
height:100%;
width:50%;
right:0;
position:fixed;
background-image:url(http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png);
background-position:right;
}
JAVA SCRIPT
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ];
var img1 = bgimgs[id];
var img2 = bgimgs[id+1];
var cnt = 2;
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
id = id + 1;
if (id==cnt) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
$(document).ready(function() {
carousel_bg(0);
});
The background-images should be changing randomly, but they don't even change at all.
OK, I see the issue in your jsFiddle. Because you're passing a string to setTimeout() that string will be evaluated only at the top level scope. But, the function name you were passing is not at the top level scope (it's in an onload handler for the jsFiddle). So, I changed the way your JS is positioned in the jsFiddle so it is now at the top level scope. I also fixed up the logic for selecting an image and it now works here: http://jsfiddle.net/jfriend00/awVYP/
And, here's a cleaned up version that does not pass a string to setTimeout() (a much better way to write javascript) that passes a local function and uses a closure to keep track of the current index: http://jsfiddle.net/jfriend00/LVGNN/
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ]; // add images here..
function next() {
if (id >= bgimgs.length) {
id = 0;
}
var img1 = bgimgs[id];
id++;
if (id >= bgimgs.length){
id = 0;
}
var img2 = bgimgs[id];
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
setTimeout(next, 1000);
}
next();
}
$(document).ready(function() {
carousel_bg(0);
});
Previous comments on earlier version so of the OP's code:
$('#body')
should be:
$('body')
or even faster:
$(document.body)
Also, your jsFiddle shows a bit of an odd issue. Your CSS has a background image on the HTML tag, but your javascript sets a semi-transparent background image on the body tag. Is that really what you want?
For testing I added another image to the array so that we got some distinction in the sorting.
function carousel_bg(id) {
var bgimgs = [ 'http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png', 'http://presotto.daterrawebdev.com/d/img/burningman_bg.png', 'http://gallery.orobouros.net/var/albums/2012/NewYorkComicCon2012/Legend-of-Korra/nycc_20121013_164625_0041.jpg?m=1354760251' ]; // add images here..
var img1 = bgimgs[id+1];
var img2 = bgimgs[id];
var cnt = bgimgs.length; // change this number when adding images..
$('#bg_left').css("background-image", "url("+img1+")");
$('#bg_right').css("background-image", "url("+img2+")");
id = id + 1;
if (id== (cnt - 1) ) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
Two changes here:
For your total image count, I am retrieving the total count of images in the array dynamically instead of by hand (bgimgs.length)
In your conditional to reset the id value, subtract the total count by 1. Since JS has zero-based indexes, not doing this will get you an undefined error (a 3 item array will spit out a value of 4 in your original code on the last iteration).
While this code does loop through your array, it's not random. That's another topic.
For those not using JQuery, simply do the following:
document.body.style.backgroundImage="url(images/mybackgroundimage.jpg)";
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.
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