Random Image refreshed after set time - javascript

so earlier I asked about creating a javascript which automatically picks an image out of the a directory randomly.
The script works perfectly, however. I would like to modify the script so that it picks an image at random to load (which it already does) then, after a set time like 10 seconds, will fade out and a new randomly picked image will fade in.
Here is the existing code:
function randomImage() {
var fileNames = [
"1.jpg",
"2.jpg",
"3.jpg"
];
var randomIndex = Math.floor(Math.random() * fileNames.length);
document.getElementById("background").background = "backgrounds/" + fileNames[randomIndex];
}
Thank you!

You can call your function after regular intervals like this. First call is to set image for the first time. If you are already using it, ignore it.
randomImage();
setInterval(randomImage,10000);

Here you go it's just like before only I added setTimeout()
pass an anonymous function which calls the randomImage() function every 10 seconds, 10000 ms.
function randomImage() {
var fileNames = [
"1.jpg",
"2.jpg",
"3.jpg"
];
var randomIndex = Math.floor(Math.random() * fileNames.length);
document.getElementById("background").background = "backgrounds/" + fileNames[randomIndex];
setTimeout(function() {
randomImage();
}, 10000);
}

Use DOMElement.style.background instead of DOMElement.background to set the background of the HTML element.
To execute certain function or expression after specific duration, use Window setInterval(). It accepts 2 arguments. First argument is Callback function and second argument is the interval.
Note: This example will change the background style of element. It will not give you fadeIn/fadeOut animation.
Try this:
function randomImage() {
var fileNames = [
"http://ryanlb.com/images/other/images/getter-dragon-1.jpg",
"http://ryanlb.com/images/other/images/getter-dragon-2.jpg"
];
var randomIndex = Math.floor(Math.random() * fileNames.length);
document.getElementById("background").style.background = 'url(' + fileNames[randomIndex] + ')';
}
randomImage();
setInterval(randomImage, 10000);
* {
padding: 0;
margin: 0;
}
html,
body {
width: 100%;
height: 100%;
}
#background {
width: 100%;
height: 100%;
background-size: 100% auto;
}
<div id="background"></div>
Fiddle here

you want to set element background url so its need like
document.getElementById("background").style.background = "url('backgrounds/" + fileNames[randomIndex]+"')";
if you want to set image url ,
document.getElementById("background").src= "backgrounds/" + fileNames[randomIndex];

Related

How to change background Image with DOM and JavaScript

Hi Everyone,
I am a beginner working on a small project in which I am facing an issue related to the background image (how I can change the background image using DOM and Javascript). I Have tried a few ways but am still on the problem side. I have used JavaScript function (random_image_picker(min,max)) for getting random image from Image_gallery. Everything going well until when I clicked on background_theme btn, the background image was supposed to be changed but not working. Every help would be appreciated.
Thanks
HTML Tag...
..Background Image....
<script>
const image_gallery = ['https://img.playbuzz.com/image/upload/ar_1.5,c_pad,f_jpg,b_auto/q_auto:good,f_auto,fl_lossy,w_480,c_limit,dpr_1/cdn/2c2dd0ea-8dec-4d49-8a95-f7b18f0b7aed/df312655-1d96-457d-88f4-cfc93c580d1d_560_420.jpg',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTwpR0X1hmpt4Kd2WviLXQGPrnUllW2UoLgtoWBoesgtFtSPFCF808bibJ8K2VhHRCki48&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxmLTuD78jeZaVR3I_xfIuvmE4tse_JuhGjQ&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSxWrBodkwbTlxbMexeQCOneifPHaOUoTFwPA&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtQMwmsMjdYfF0W0cyMPX673aKVK3m8sSDjg&usqp=CAU']
function random_image_picker(min, max) {
let a = Math.floor(Math.random() * (max - min + 1) + min);
return image_gallery[a];
}
let background_theme = document.querySelector('#background_theme');
let main = document.getElementsByTagName('main');
background_theme.addEventListener('click',function(){
main.style.backgroundImage = URL(random_image_picker(0,4))
})
</script>
BackgroundImage should be a string
The style.backgroundImage property accepts a string.
you can apply it using a template string `url(${random_image_picker(0, 4)})`
or using a regular concat like "url("+random_image_picker(0, 4)+")"
getElementsByTagName('main') return an array of elements
when you use getElementsByTagName you'll receive an array. If there's only 1 element to apply the background image to. you may select the first element using an 0 index.
document.getElementsByTagName('main')[0];
const image_gallery = ['https://img.playbuzz.com/image/upload/ar_1.5,c_pad,f_jpg,b_auto/q_auto:good,f_auto,fl_lossy,w_480,c_limit,dpr_1/cdn/2c2dd0ea-8dec-4d49-8a95-f7b18f0b7aed/df312655-1d96-457d-88f4-cfc93c580d1d_560_420.jpg',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTwpR0X1hmpt4Kd2WviLXQGPrnUllW2UoLgtoWBoesgtFtSPFCF808bibJ8K2VhHRCki48&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxmLTuD78jeZaVR3I_xfIuvmE4tse_JuhGjQ&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSxWrBodkwbTlxbMexeQCOneifPHaOUoTFwPA&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtQMwmsMjdYfF0W0cyMPX673aKVK3m8sSDjg&usqp=CAU'
]
function random_image_picker(min, max) {
let a = Math.floor(Math.random() * (max - min + 1) + min);
return image_gallery[a];
}
let background_theme = document.querySelector('#background_theme');
let main = document.getElementsByTagName('main')[0];
background_theme.addEventListener('click', function() {
main.style.backgroundImage = `url(${random_image_picker(0, 4)})`
})
main {
width: 400px;
height: 400px;
border: 2px solid lime;
}
<main>
<button id="background_theme">swap theme</button>
</main>

Execute jQuery function after first is complete

I have created a page where I have multiple functionality done but stuck with timing of it, if you see the page example here in JSFiddle.
When you open the page, it will first run a loader and when the loader is complete there are multiple boxes, which is showing one by one but in currently its not happening, Loader is loading fine and then in the next step where centered columns has to appear one by one, the first four columns loads by default and then other div loads one by one.
My question is, how can I execute a function and execute another another function once the previous is complete.
For loader I have the following:
//--------- process bar animation
var showText = function (target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
}
}
var width = 100,
perfData = window.performance.timing, // The PerformanceTiming interface represents timing-related performance information for the given page.
EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
time = parseInt((EstimatedTime/1000)%60)*100;
showText("#msg", "Welcome to the Company Group", 0, width);
// Loadbar Animation
$(".loadbar").animate({
width: width + "%"
}, time);
// Loadbar Glow Animation
$(".glow").animate({
width: width + "%"
}, time);
// Percentage Increment Animation
var PercentageID = $("#precent"),
start = 0,
end = 100,
durataion = time;
animateValue(PercentageID, start, end, durataion);
function animateValue(id, start, end, duration) {
var range = end - start,
current = start,
increment = end > start? 1 : -1,
stepTime = Math.abs(Math.floor(duration / range)),
obj = $(id);
var timer = setInterval(function() {
current += increment;
$(obj).text(current + "%");
//obj.innerHTML = current;
if (current == end) {
clearInterval(timer);
}
}, stepTime);
}
// Fading Out Loadbar on Finised
setTimeout(function(){
$('.preloader-wrap').fadeOut(300);
$('.loader-wrap').fadeOut(300);
$('.main-wrapper').fadeIn(300);
$('body').addClass('bg');
}, time);
For showing div one by one in next step I have the following code:
$(".column-wrapper").each(function(index) {
var $this = $(this);
setTimeout(function () { $this.addClass("show"); }, index * 1000);
});
I use trigger and on for those kind of things. You had a lot of code, so sorry, I didn't want to read all of that but this is a simplified example.
https://jsfiddle.net/2d6p4L6k/1/
$(document).ready(function(){
var action = function(){
$('div.one').css('background-color', 'green');
/* do whatever you want to do */
/* then trigger(call) another function */
$(document).trigger('hello-action');
};
var hello = function() {
$('div.two').css('background-color', 'fuchsia');
};
/* just listen if anything triggers/calls "hello-action" */
/* if so call function named hello */
$(document).on('hello-action', hello);
setTimeout(action, 1500);
});
div {
width: 50px;
height: 50px;
background-color: orange;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">one</div>
<div class="two">two</div>
Note: To keep it simple we trigger and listen on $(document) which is really just to keep it simple. A better approach would be to have a wrapper element, and then you can do exactly the same (trigger and listen) just on that element and not on the entire document. You can find more details on the jQuery API .trigger()

Using JQuery to create animation frames from PSD layers

I have a PSD file with a bunch of layers that are frames for an animation. How can I create an animation from this using JQuery/JavaScript?
Will I have to save each layer as a separate image, is there a way to have the one image with multiple layers animated? To clarify, I don't want the actual image to move, I just want different layers to be displayed as if they were frames of an animation. What's the standard way this is done with JavaScript?
Thanks!
Here is a fiddle that demonstrates the javascript timer + individual images approach.
Fiddle: http://jsfiddle.net/ZVFu8/2/
The basic idea is to create an array with the names of your images.
var img_name_arr = [];
var img_name_root = "anim-";
var img_name_ext = ".gif";
var num_images = 12;
// init arr of img names assuming frames are named [root]+i+[extension]
for (i = 0; i<=num_images; i++) {
img_name_arr.push(img_name_root + i + img_name_ext);
}
For the animation, use setInterval(). In javascript, an interval executes periodically. You specify the code to execute and the interval at which the code should be run (in milliseconds).
Every time your interval is called, you can display a new image by setting the "src" attribute of the image tag to the next index in the image_name array.
// Create an interval, and save a handle to the interval so it can be stopped later
anim_interval = setInterval(function() {
$("#player").attr("src", s + img_name_arr[(anim_frame++ % num_images)+1] );
}, frame_interval);
Depending on how long your animation is and how large each image file is, it might be necessary to optimize this by pre-loading these images. Before the animation starts, you could create an img tag for each image and hide it. Then, instead of altering the "src" attribute to change the image, you would actually hide the current image and un-hide the next image in the previous image's place.
Here is the full code if you wish to run this locally:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a id="anim_control" href="">Start</a>
<img id="player" src="" />
<script>
var s = "http://" + atob("YmVucmlkb3V0LmNvbQ==") + "/";
var img_name_arr = [];
var img_name_root = "anim-";
var img_name_ext = ".gif";
var num_images = 12;
var framerate = 1; // Desired frames per second
var frame_interval = 1000/framerate;
$(function(){
// Document is ready
// init arr of img names
for (i = 0; i <= num_images; i++) {
img_name_arr.push(img_name_root + i + img_name_ext);
}
var anim_interval = null;
var playing = false;
var anim_frame = 0;
// Define an interval that will execute every [frame_interval] milliseconds
$("#anim_control").on("click", function(e) {
e.preventDefault();
if (playing == true) {
playing = false;
$(this).html("Start");
clearInterval(anim_interval);
} else {
playing = true;
$(this).html("Stop");
anim_interval = setInterval(function() {
//console.log(s + img_name_arr[(anim_frame++ % num_images)+1]);
$("#player").attr("src", s + img_name_arr[(anim_frame++ % num_images)+1] );
}, frame_interval);
}
});
});
</script>
<style>
#player {
width: 320px;
height: 240px;
border: 1px solid #000;
}
</style>

JavaScript, How to change the background of a div tag every x seconds

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)";

Adding random class to the div

At the moment in my game, when it is complete a random image is passed to the "reveal-wrapper" to display at the end.
I still want to do this but instead of doing it this way I would like to add a random class each time to the "revael-wrapper" to make it ".reveal-wrapper .image1" for example. There will be 5 different images and I want it to pick one at random each time.
The code for it at the moment is as follows:
$(document).ready(function () {
bgImageTotal = 5;
randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
imgPath = ('images/reward-images/' + randomNumber + '.png');
$('.reveal-wrapper').css('background-image', ('url("' + imgPath + '")'));
});
Any ideas how I would add a random class instead?
You've already got the logic in place, you just need to add the class. Try this:
$(document).ready(function () {
bgImageTotal = 5;
randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
$('.reveal-wrapper').addClass('image' + randomNumber);
});
All you then need to do is setup the classes in your CSS:
.image1 { background-image: url('images/reward-images/1.png'); }
.image2 { background-image: url('images/reward-images/2.png'); }
.image3 { background-image: url('images/reward-images/3.png'); }
.image4 { background-image: url('images/reward-images/4.png'); }
.image5 { background-image: url('images/reward-images/5.png'); }
Since you already have the random numbers, and provided your images have the same filename structure (image1, image2, ect.)
$('.reveal-wrapper').addClass('image' + randomNumber);
Rory has a fine solution, but if you're so curious here's something a little more general:
function add_rand_class (classes, elem) {
$(elem).addClass(classes[Math.random() * classes.length >> 0]);
}
pass the function an array of class strings and the element on which you want the class, and you're good to go.

Categories