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;
}
Related
I have designed a game where In the first page I ask the name of the user( background used- bgimg1)
On the click of a certain button, I go to the next page(I changed the background again) What I tried to do this was background(bgimg2) and I also tried putting [changeImage and changeAnimation, no error and still did not work], so I tried putting bgimg = bgimg2, It worked!
Now I displayed another button, and on the click of the button I called a function (name - attack),
In the function I tried to use bgimg2 = bgimg3;
It did not work, what should I do to change the background again, please suggest how to change the background, I think maybe if I preload all the images in the same variable, then how will I display different backgrounds in different functions;
Code
function preload() {
bgimg = loadImage("images/LayoutGH.png");
bgimg2 = loadImage("Screen 1/image.jpg");
bgimg3 = loadImage("Attack/attackButtonbg.jpg");
}
Simply use a css class with each images, and change on your command
(function ()
{
const bgClass = [ 'bg1', 'bg2', 'bg3' ]
, btChange = document.getElementById('bt-bg')
;
let noBg = 0;
document.body.className = bgClass[noBg];
btChange.onclick=_=>
{
noBg = ++noBg %3;
document.body.className = bgClass[noBg];
}
})();
body {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
.bg1 { background-image: url(https://picsum.photos/id/251/500/300.jpg); }
.bg2 { background-image: url(https://picsum.photos/id/259/500/300.jpg); }
.bg3 { background-image: url(https://picsum.photos/id/254/500/300.jpg); }
<button id='bt-bg'> change </button>
I am trying to make it so that when the user clicks on a restyle button it will change the background to the images stored in my folder. I have a couple, and then you can choose to reset back to the normal image, however for some reason I cant get it to work, any help would be great on this matter:
HTML buttons
ReStyle
Reset
Javascript
var counter = 0;
function changeLook(){
counter += 1;
switch (counter) {
case 1:
document.body.style.backgroundImage = "../Image/BackgroundImage2.jpg";
break;
case 2:
document.body.style.backgroundImage = "../Image/BackgroundImage3.jpg";
break;
case 3:
counter = 0;
document.body.style.backgroundImage = "../Image/BackgroundImage4.jpg";
break;
}
}
function changeBack(){
document.body.style.backgroundImage = "../Image/BackgroundImage1.jpg";
}
CSS
body {
padding-top: 23px;
padding-bottom: 10px;
background: url('../Image/BackgroundImage1.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Just add url(image path) like:
document.body.style.backgroundImage = "url(../Image/BackgroundImage2.jpg)";
var counter =0;
function changeLook() {
counter += 1;
switch (counter) {
case 1:
document.body.style.backgroundImage = "url(http://placehold.it/200x200)";
break;
case 2:
document.body.style.backgroundImage = "url(http://placehold.it/300x300)";
break;
case 3:
counter = 0;
document.body.style.backgroundImage = "url(http://placehold.it/400x400)";
break;
}
}
function changeBack(){
document.body.style.backgroundImage = "url(http://placehold.it/200x200)";
}
body {
padding-top: 23px;
padding-bottom: 10px;
background: url('http://placehold.it/200x200') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
ReStyle
Reset
It's likely that you're referencing your file paths incorrectly. Check your developer console within your browser. Do you see any 404 errors?
Additionally, you can simplify your changeLook function by using a modulus:
var counter = 1;
function changeLook(){
counter = counter % 4 + 1;
document.body.style.backgroundImage = "../Image/BackgroundImage" + counter + ".jpg";
}
function changeBack() {
document.body.style.backgroundImage = "../Image/BackgroundImage1.jpg";
}
You absolutely could use your current code. If it isn't working, then the issue is likely that your relative paths within your CSS files for your background properties are incorrect.
It's important to remember that the paths used within a CSS file will be relative to the CSS file itself and not where it is referenced. However, when you use the relative references in your Javascript code, it will be made relative to where the Javascript is referenced (i.e. your HTML document).
You may want to consider defining CSS styles to handle these changes :
body.background1 {
background: url('../Images/Image1.jpg');
}
body.background2 {
background: url('../Images/Image2.jpg');
}
/* Continue as necessary */
And then simply update the class for your <body> element using Javascript :
// Use the counter to determine which style to apply
switch (counter) {
case 1:
document.body.className = "background1";
break;
case 2:
document.body.className = "background2";
break;
case 3:
counter = 0;
document.body.className = "background3";
break;
}
Example
You can see a very basic example of this here and demonstrated below :
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];
I'm currently working on a site, where I want the background on the index (in this case an image.) to change every time you enter the site. So this is the solution that I came up with:
var Index = {
Actions: {
setBackground: function() {
var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg'];
var random = images[Math.floor(Math.random() * images.length)];
alert(random);
$("body").css({'background-image': 'url("../img/backgrounds/' + random + '");'});
}
}
}
Index.Actions.setBackground();
but for some reason, the background stays white. I did also try the actual switching like this:
document.body.style.backgroundImage = "../img/backgrounds/" + random;
But that also did nothing.
Please note that the console is empty.
Here is the CSS for the body object:
body {
background-size:cover;
background-position:center;
background-attachment:fixed;
width:100%;
height:100vh;
position:relative;
}
Is there a reason that this wont work? And if so, how to fix it...
Thanks.
Try this; $("body").css('background-image', 'url("../img/backgrounds/' + random + '")');
jsfiddle demo
Correct syntax; .css( propertyName, value )
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.