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.
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>
For my web design class we were instructed to do a one week exercise where we figure out how to take a creative approach to a clock that tells the time and temperature. This class is graded on creativity, I am allowed and encouraged to use plugins.
For my idea I think it would be interesting to change the background of my site every hour to match with the corresponding time. I have multiple images of a flower blooming and closing that I think would be interesting to correspond with the time of day.
What should I do to take what I already have and make it so that I can change the background image every hour? Is it something that should correspond with my existing javascript plugin clock, or is it a separate implementation entirely? Thanks in advance!
I don't want the image to change after a set interval, I want certain times in the day to correspond with the background image.
body {
background-color: black;
margin-left: 5%;
margin-right: 5%;
}
#txt {
color: white;
float: left;
font-family: OpenSans;
font-size: 90px;
margin: 20px;
}
#weather {
color: white;
float: right;
font-family: OpenSans;
font-size: 40px;
margin: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Blooming Time And Temperature</title>
<link href="css/format.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
function startTime() {
document.getElementById('txt').innerHTML =
moment().format("hh:mm A");
var t = setTimeout(startTime, 1000);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
<script>
$(document).ready(function() {
$.simpleWeather({
location: 'Brooklyn, NY',
woeid: '',
unit: 'f',
success: function(weather) {
html = '<p>'+weather.temp+'°'+weather.units.temp+'</p>';
html += '<div id="city">'+weather.city+', '+weather.region+'</div>';
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
});
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
<div id="weather"></div>
</body>
</html>
You need to get hour of the day on hourly basis. According to the hour, you can change background using jQuery:
$(document).ready(function() {
setInterval(function(){
var hour = new Date().getHours();
if(hour > 7 && hour <= 12)
{
// It's morning
$('body').css('background', 'url(url-to-image-one) no-repeat');
}
else if(hour > 12 && hour < 18)
{
// It's noon
$('body').css('background', 'url(url-to-image-two) no-repeat');
}
else
{
// It's night
$('body').css('background', 'url(url-to-image-three) no-repeat');
}
}, 1000 * 60 *60);
});
To keep this simple, you could setInterval(). Here's how it works: http://www.w3schools.com/jsref/met_win_setinterval.asp
What I would do is check the current time, then get the difference between now and the next hour (that is, if it was 10:30 and I wanted to know how much time was between 10:30 and 11), do a setTimeout() for that amount of time in milliseconds, and then call a function that begins the setInterval() function that will be called every hour.
Hope this helps!
this is a code from John duckett's javascript and jquery book
var today= new Date();
var hourNow = today.getHours();
var greeting;
if (hourNow > 18) {
greeting= 'Good evening!';
else if (hourNow > 12) {
greeting = ' Good afternoon!';
else if (hourNow > 0) {
greeting = 'Good morni ng!';
else {
greeting = 'Welcome! ' ;
}
document .write( ' <h3>' +greeting + ' </ h3> ');
the value of the variable greeting is change base on the if condition. See Date and getHours() method
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;
}
So, I've been trying to get this form to work (css and javascript), but I'm stuck on something: i have the form, and everything's basically working, excpet that i have a container for the form div: formbody, and a container for the submit, clear, etc.
The top div is set to height:auto; position:absolute; and the bottom is set to, nothing. it just had a width.
When the user clicks on the submit button, the formbody will need to resize, but i don't know how to get the new size of the form in order to set the position of the bottom div.
I just added more of the css - there's a background div that just holds the template open for the form -- I had that set to relative -- but formbody has a position absolute because the height needs to be auto in order to resize for the errors (and when i set it to auto without position:absolute, formbody shrank to 20px).
.background {
width: 0px;
height: 700px;
position: relative;
z-index:999;
}
.formbody {
background-image: url('');
background-repeat: no-repeat;
background-position: left bottom;
position:absolute;
left:0px;
top:50px;
width:700px;
height:auto;
padding-bottom:20px;
border:1px solid #d2d2d2;
}
.bottom {
width:700px;
}
Would this work? (Here's a live preview: http://jsfiddle.net/rcMGn/1/)
Basically what I'm doing here is getting the first node with class formwidth (as per your css) and using the DOM model to acquire its style properties.
The function getElementsByClass will return an array of all elements in the document with class formwidth (and I'm supposing there's going to be only one) and getting the first element from the array (which is supposed to be 1) and then styling it.
You don't need to care about the function...
To get the width just the first line of the code below...
formWidth = getElementsByClass('formbody',null,'form')[0].offsetWidth;
To get the height, use this one:
formHeight = getElementsByClass('formbody',null,'form')[0].offsetHeight;
and copy the function from the files of Dustin Diaz, the function below...
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
something like this
<script>
var formbody_width= $(".formbody").width();
$(".submit").live("click", function) {
$(".formbody").css("height", formbody_width + 300 + "px");
}
</script>