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.
Related
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>
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];
Any help here is much appreciated. I would like to use jQuery to solve the following...
There are two divs. I would like to randomly fade in one of the divs (green or red), wait a few seconds, then fade it away. Then randomly fades in another one. I've tried using math.random();but I can't seem to get it working correctly.
So basically it chooses either the red or green div.. fades it away after a few seconds, randomly chooses the red or green div... then fades it away after a few seconds. And It just keeps repeating.
html:
<div id="one">This is the first block</div>
<div id="two">This is the second block</div>
css:
#one {
background: red;
width:300px;
height:100px;
}
#two {
background: green;
width:300px;
height:100px;
}
Give both divs a class name like .fade for easier to manage.
Then you can do like this:
(function randomFade() {
var fadeDivs = $('.fade'),
el = fadeDivs.eq(Math.floor(Math.random() * fadeDivs.length));
el.fadeIn('1000').delay(2000).fadeOut('1000',randomFade);
})();
Fiddle Demo
You could do this:
function fadeRandomly() {
// fade both out at first
$('#one').fadeOut(/* duration */);
$('#two').fadeOut(/* duration */);
if (Math.random() > 0.5) {
$('#one').fadeIn(/* duration */);
} else {
$('#two').fadeIn(/* duration */);
}
}
setInterval(fadeRandomly, /* duration between animations */);
This should work:
var rnd = Math.floor(Math.random() * 2) + 1;//outputs either 1 or 2
if (rnd == 1) {
$('#one').fadeIn(500).delay(500).fadeOut(500);
} else {
$('#two').fadeIn(500).delay(500).fadeOut(500);
}
Hope this helps!
something like: I added a function just in case you have more divs to deal with you and you want to expand the scope of your fades.
var a = ['one', 'two']; // the name of your divs
function fadeRandomDiv(min, max) {
var divtofade = a[Math.floor(Math.random() * (max - min + 1) + min)];
// delay 4 seconds, then fade out
jQuery( "#" + divtofade ).fadeIn( "slow" ).delay(4000).fadeOut("slow");
}
fadeRandomDiv(1, a.length - 1)
if you want to repeadedly call it.
// every 3 seconds call the function
setInterval(function(){
fadeRandomDiv(1, a.length - 1);
}, 3000);
To begin, here is the page.
I've attempted the Javascript code without success, so I will try to explain my current setup.
my body has an ID of #homepage. This is the only page I will need this code for, so I've assigned that ID. The following is the CSS to access the image and cover the page:
body#homepage {
background-attachment: fixed;
background-image: url(../images/bg/4.jpg);
background-repeat: no-repeat;
background-position: center bottom;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
There are 4 images in the "../images/bg" folder, numbered 1 through 4. I simply want the images to change between the 4 upon page load, but I need to keep the images styled as they are in the current CSS.
Since I am only vaguely familiar with Javascript, I believe I'm getting something very simple wrong in the Javascript. I would appreciate someone spelling this out for me in specific detail. Thanks so much!
try this
var randomImage = Math.floor((Math.random()*4)+1);
var homePage = document.getElementById('homepage');
homePage.style.backgroundImage='url("..\/images\/bg\/'+randomImage+'.jpg")';
with Jquery
$(document).ready(function(){
var num = getRandomArbitrary(1,4);
$('#homepage').css("background-image",'../images/bg/' + num + '.jpg')
});
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
document.getElementById('homepage').style.backgroundImage = 'url(/whatever/img' + Math.floor( Math.random()*4 ) + '.png)';
First you need to get random number from 1 to 4.
I'll show you pure JavaScript and jQuery ways to do it:
JavaSript way:
//get random number from 1 to 4 and assign '.jpg' - or other format you need
var randomImage = "..\/images\/bg\/" + Math.floor((Math.random()*4)+1) + '.jpg';
//get body by ID
var homePageBody = document.getElementById('homepage');
//asign random image to body
homePageBody.style.backgroundImage=randomImage;
jQuery way:
$(document).ready(function () {
var randomImage = '../images/bg/' + randomFromTo(1, 4) + '.jpg';
//set background to body #homepage
$('#homepage').css("background-image", randomImage)
});
//define randomizer function
function randomFromTo(rfrom, rto) {
return Math.random() * (rfrom - rto) + rfrom;
}
Basically I'm trying to merge the two scripts below for a project. My goal is to keep the functionality of the first link, where it fades in random divs at different intervals, but attach it to PaulPRO's version, in that it keeps looping over and over again, say every 5 seconds. Any help is greatly appreciated!
http://jsfiddle.net/cMQdj/1/ (thanks to mblase75)
http://jsfiddle.net/Paulpro/G4pxq/ (thanks to PaulPRO)
Hows this ->
http://jsfiddle.net/G4pxq/9/
(function fadeInDiv(){
var divs = $('.fadeIn');
var elem = divs.eq(Math.floor(Math.random()*divs.length));
if (!elem.is(':visible')){
elem.fadeIn(Math.floor(Math.random()*1000),fadeInDiv);
} else {
elem.fadeOut(Math.floor(Math.random()*1000),fadeInDiv);
}
})();
Update
Maintaining position / order :
http://jsfiddle.net/G4pxq/12/
$('.fadeIn').before('<div> </div>');
(function fadeInDiv() {
var divs = $('.fadeIn');
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.fadeIn(Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.fadeOut(Math.floor(Math.random() * 1000), function() {
elem.before('<div> </div>');
fadeInDiv();
});
}
})();
I think you have your examples reversed.
If you want to loop Paul's example, just surround his code in a setInterval method.
setInterval($('.fadeIn').before('<div> </div>'), 2000);