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 :
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>
The first section of my website contains a picture. I want the picture to change based on the local time. For example between 6 AM until 6 PM the "day picture" will be shown, and the rest of the time the "night picture" will be shown. I have two classes in my CSS file one called Day the other Night:
.day {
background-image: url("./css/images/daymode.jpg");
background-size: cover;
}
.night {
background-image: url("./css/images/nightmode.jpg");
background-size: cover;
}
this is the HTML section I would like to change its the background:
<section class="home-section section-hero overlay slanted" id="home-section">
that's my JavaScript file:
$(document).ready(function() {
var d = new Date();
var n = d.getHours();
if (n > 18 || n < 6)
// If time is after 7PM or before 6AM, apply night theme to ‘body’
document.body.className = "night";
if (n > 6 && n < 18) document.body.className = "day";
});
I can't figure out how to put these day and night classes in the same class of the section element so it will recognize them and I can control it with the js file.
Any help will be appreciated! :)
You are close, but if you want to target only changing the background on your section, then you need to change the CSS selectors slightly. While you CAN have both a 'day' and 'night' class, it is easier to just have a default, and then an overridden 'night' theme.
Since you are already using $(document).ready, I'll assume you have jQuery included, so I've modified your function to take advantage of this and preserving whatever additional classes may have already been present on the body.
$(document).ready(function() {
$('body').toggleClass('night',IsNight());
setInterval(function(){
$('body').toggleClass('night',IsNight());
},60000);
});
function IsNight()
{
var d = new Date();
var n = d.getHours();
return (n >= 18 || n < 6);
}
#home-section {
background-image: url("./css/images/daymode.jpg");
background-size: cover;
}
.night #home-section {
background-image: url("./css/images/nightmode.jpg");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="home-section section-hero overlay slanted" id="home-section">blah</section>
Here is the same thing, slightly modified so that you don't have to wait for day/night. This changes every second instead and uses color instead of background-iamge.
$(document).ready(function() {
setInterval(function(){
$('body').toggleClass('night');
},1000);
});
#home-section {
background-image: url("./css/images/daymode.jpg");
background-size: cover;
color: yellow;
}
.night #home-section {
background-image: url("./css/images/nightmode.jpg");
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="home-section section-hero overlay slanted" id="home-section">blah</section>
You can use if{..}else{..}
for you understanding i have set the time of day you can comment it and set it to current time
var d = new Date('Thu Feb 20 2020 07:35:09 GMT+0530 ');
//var d = new Date();
var n = d.getHours();
if (n > 18 || n < 6) {
// If time is after 7PM or before 6AM, apply night theme to ‘body’
document.body.className = "night";
} else {
document.body.className = "day";
}
.day {
background-image: url("./css/images/daymode.jpg");
background-size: cover;
background-color: orange;
}
.night {
background-image: url("./css/images/nightmode.jpg");
background-size: cover;
background-color: black;
}
Since you have an ID on your section element, you can more easily do:
var section = document.getElementById('home-section');
var period;
// your logic to define whether it's day or night, and it's set to 'period'
// then, remove previous set classes
section.classList.remove('day');
section.classList.remove('night');
// finally, set the recently defined period
section.classList.add(period);
This way, since both of your day and night classes share the background-size: cover property, you can move it into your styles for the #home-section css rules.
I have an html string in which I want to replace url of background-image. But wasn't able to do it.
This code looks like html but actually its a string which have html data.
MY string
var html ="
.reg-inner {
background-image: linear-gradient),url(http:\\abc.com);
}
.reg-left {
background-image: linear-gradient),url(http:\\abc.com);
background-size: cover;
}
.reg-right {
background-image: linear-gradient),url(http:\\abc.com);
}"
I want to replace the url after the .reg-left.
I applied this regex but it will replace first one.
html.replace(/url\((['"]?)(.+?)\1\)/, "url(" + replacableImage + ")");
Your HTML string is not HTML. It is CSS.
Your regex works. You need to add a g to get all of them
Also you cannot have newlines in a JS string - you need backticks to allow the linefeeds
const replacableImage = "abc.jpg";
let CSS =`
.reg-inner {
background-image: linear-gradient),url(http:\\abc.com);
}
.reg-left {
background-image: linear-gradient),url(http:\\abc.com);
background-size: cover;
}
.reg-right {
background-image: linear-gradient),url(http:\\abc.com);
}`
CSS = CSS.replace(/url\((['"]?)(.+?)\1\)/g, "url(" + replacableImage + ")")
console.log(CSS)
If you only want one of them, you can run a replace function or a split+map+join
const replacableImage = "abc.jpg";
let CSS = `
.reg-inner {
background-image: linear-gradient),url(http:\\abc.com);
}
.reg-left {
background-image: linear-gradient),url(http:\\abc.com);
background-size: cover;
}
.reg-right {
background-image: linear-gradient),url(http:\\abc.com);
}`
CSS = CSS.split('.reg-').map(
str => str.indexOf('left') === 0 ?
str.replace(/url\((['"]?)(.+?)\1\)/, `url("${replacableImage}")`) : str
)
.join('.reg-')
console.log(CSS)
Was wondering if there was a way to condense this and have it go on
li:nth-child(1){
background-image: url(1.jpg);
}
li:nth-child(2){
background-image: url(2.jpg);
}
li:nth-child(3){
background-image: url(3.jpg);
}
li:nth-child(4){
background-image: url(4.jpg);
}
li:nth-child(5){
background-image: url(5.jpg);
}
And so on and so on.
Would there be a way to have this go on with pure css variables or is there an easier solution with javascript?
CSS has no way to relate, as yet, the index of the element to a property of that element's CSS; with JavaScript it's easy enough:
var liElements = document.querySelectorAll('li');
[].forEach.call(liElements, function (li, index) {
li.style.backgroundImage = 'url(' + index + '.jpg');
});
With CSS it's possible, in future, that the following may work (but this is pure speculation):
ul {
counter-reset: liCount;
}
ul li {
counter-increment: liCount;
background-image: url(counter(liCount) '.jpg');
}
This does not work in any current browsers, and may never work in any browser. As noted, this is purely speculative.
If you don't know how many children you have, you'll want to use JS. Or, if you do, but don't want to type it all out, or have a max, then PHP which could just make the CSS file which would be faster than JS doing it after the load.
var liElems = document.getElementsByTagName('li');
for(var i = 0; i < liElems.length(); ++i){
li.style.backgroundImage = 'url("' + i + '.jpg")';
}
Or, for PHP:
for($idx = 0; $idx < MAGIC_NUM; ++$idx){
print("li:nth-child($idx){");
print(" background-image: url($idx.jpg);")
print("}\n");
}
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;
}