getHours(), show and hide - javascript

I'm currently working on my first website and have run into an issue that I just can't pass. I am using JavaScript to show and hide elements in my HTML (sounds easy enough right?) But it's not working the way it should. Even when I have an alert on the page that shows the number returned by variable 'hours', there is some issue when showing the correct information.
var today = new Date();
var hours = today.getHours();
alert(hours)
let day = document.querySelector('.day')
let night = document.querySelector('.night')
if (hours > 9 || hours < 12) {
day.style.display = "block";
night.style.display = "none";
}
else {
day.style.display = "none";
night.style.display = "block";
let blurred = document.querySelector('h1')
blurred.classList.add('blur');
}
Not to mention that eventually it should work with getUTCHours, however thought I would try this way first.

I think you specified a wrong if statement since an hour is always greater than 9 or less than 12.
Probably you meant something like if (hours >= 9 && hours <= 12)?

Related

How to properly add an image through JavaScript to a webpage

I am following along in a tutorial that creates a dynamic webpage. The webpage is supposed to show the time and an image that updates according to whatever hour it is. However, the way the instructor is inserting his image is new to me and I am not sure where I am messing up but no image at all is being displayed on the page.
let today = new Date(),
hour = today.getHours();
if(hour < 12) {
// Morning
document.body.style.backgroundImage = "url('../images/Morning.jpg')";
greeting.textContent = 'Good Morning';
} else if(hour < 18) {
// Afternoon
document.body.style.backgroundImage = "url('../images/Evening.jpg')";
greeting.textContent = 'Good Afternoon';
} else {
// Evening
document.body.style.backgroundImage = "url('../images/Night.jpg')";
greeting.textContent = 'Good Evening';
}
}```
I get no error messages with the following function after calling it. However, no image is being displayed.
url('../images/Morning.jpg')";
has to be a valid URL. Let's say your HTML file was www.example.com/foo/index.html. There would have to be a www.example.com/images/Morning.jpg file, or else you won't see anything.
This is especially true if your URL before was "Morning/jpg", as that's not a valid URL (well, technically it is, but it almost certainly isn't valid for your case).

Timezone specific hide/show element script

Hi first time posting here so bear with me.
I've got a live stream that I want to show on Sundays between 6am and 2pm (CEST - Central European Summer Time)
I've got the first part down but how do I make it timezone specific? Make sense?
$(document).ready(function() {
var d = new Date();
var n = d.getDay();
var hour = d.getHours();
if(n == 0 && hour >= 6 && hour < 14)
{
$(".stream").show();
} else {
$(".stream").hide();
}
} );
PS I understand this doesn't hide it completely outside of those times and that's fine. I'm just looking for a solution that works on the client side.

setInterval and 12 hour clock in javascript

I want to write a script that changes the hour displayed inside a <span> every second, starting from 8AM, and which keeps repeating like a 12 hours clock (11AM, 12PM, ..., 11PM, 12AM, 1AM, ...).
The image will change at 8AM and 8PM. At 8PM, the image will change to a sleeping face, and at 8AM the image will change back to a smile face. However, that is not a problem.
The problems are:
When I set var hour = Number(document.getElementById("time").textContent); then setInterval repeats the time without any problem. However, when I set var hour = 8 instead, and keep same code, then setInterval repeats only once. Can you let me know why it is like that and how to fix it with var hour = 8?
When the hour is repeatedly increased, I cannot make it smart to change back to AM when it reaches to 12 after passing noon (12PM). For example, the code works fine from 8AM to 11PM but when it reaches to 12, the PM does not change to AM. Can you show me how to fix it?
Lastly when I change var period = "AM" instead of using DOM getElementByID like above and keep same code, then it runs to 1PM and then changes to 2AM and never changes to PM again. Can you explain to me why it happens?
If you do not know what I am talking about, you can run my code and to understand more.
Here is the HTML:
<h2>Life goes on!</h2>
<p>The current time is : <span id = "time">8</span> <span id = "period"> AM</span></p>
<img id = "emoticon" src = "smile.gif" alt = "awake">
And here is my JavaScript code:
setInterval(function () {
var hour = Number(document.getElementById("time").textContent);
hour++;
var period = document.getElementById("period").textContent;
if (hour >= 12) {
hour = hour - 12;
period = "PM";
}
if (hour == 0) {
hour = 12;
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);
Let me explain the problems of your code, using the same three points you made:
Your problem about var hour = 8; is that, if you set the hour inside the setInterval callback, your hour will be set to 8 at any second. Therefore, your setInterval doesn't work only once, but it gets run infinite times setting the time always to 9. To avoid this, you can move the variable outside and make it global, setting it to 8 before starting the setInterval.
To change "PM" back to "AM" when it reaches 12PM, just add an if statement (or, better, a ternary operator, like I did in the snippet below) to check if the period is either "PM" or "AM", and behave consequently. Also, be careful with the check: if you check directly on .textContent be sure that the text inside the <span> doesn't have any trailing space: use .trim() to remove extra spaces at the beginning and at the end of the string.
This is the same problem of point 1: you should make the variable period global, and then start the setInterval.
The logic of the following script is simple:
Increase the hour by 1
If the new hour equals 12, then switch to "PM" or back to "PM"
If the new hour is greater than 12, then reset it to 1
Display hour and period
Change from smile.gif to sleep.gif when it's 8PM, and vice versa when it's 8AM.
I also made some little changes to make code easier and faster to read. Here is a working code snippet:
var hour = 8,
period = "AM";
setInterval(function() {
if (++hour >= 12) {
if (hour > 12) hour = 1;
else period = (period == "PM") ? "AM" : "PM";
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);
<h2>Life goes on!</h2>
<p>The current time is: <span id="time">8</span> <span id="period">AM</span></p>
<img id="emoticon" src="smile.gif" alt="awake">
Here it is, it works fine now, give it a try clicking on "Run code snippet".

Android-Esque Time Entry Widget doesn't work when minutes section is below ten

I'm trying to make a "widget" used for controlled time entry that uses up and down arrows to increment each section in addition to allowing you to type the values in by hand. It worked fine(looping over from 12 to 1 and 59 to 1 ect.), but when I added a section that formatted the minutes properly when the value was below 10, it started acting up.
Pressing down acts normally until 10 where it displays, "10" then "09" then "0-1".
Pressing up after you get to "0-1" goes to "01" but when you get to "08", it goes back to "01".
function minFix(mins)
{
if ( mins <= 9)
{
mins = "0" + String(mins);
document.getElementById("mins").value = mins;
}
else
{
document.getElementById("mins").value = mins;
}
}
function minUp()
{
var mins = parseInt(document.getElementById("mins").value);
if (mins == 59)
{
mins = 1;
minFix(mins);
}
else
{
mins = (mins+1);
minFix(mins);
}
}
function minDown()
{
var mins = parseInt(document.getElementById("mins").value);
if (mins == 1)
{
mins = 59;
minFix(mins);
}
else
{
mins = (mins-1);
minFix(mins);
}
}
The minUp and minDown are called by the up and down arrows respectively and the textbox that displays mins has an ID of mins.
I'm sure I'm missing something simple but I can't figure it out right now so any help would be much appreciated.
this has to do with your zero that you're appending. It makes your number into a octal number, so when you read it back in, it's not being read as a decimal number. Take a look at how parseInt works and you'll understand. You need to remove the leading zero before parsing.
Scroll down for the parseInt function here: http://www.javascripter.net/faq/convert2.htm
so this line var mins = parseInt(document.getElementById("mins").value);
should be
var mins = parseInt(document.getElementById("mins").value.replace(/^0+/,""));
Oh, and welcome to Stack! please don't forget to up-vote the answers that you feel are best, and give the green checkmarks to those that you feel are the correct ones.

To change a css style depending on time of day (javascript)

im trying to write a little .js file to change a css style from display:block to display:none depending on the time of day, 08.30 to 17.00 display block and 17.00 to 08.30 display none.
Here's what i have so far:
<script language="JavaScript">
day=new Date() //..get the date
x=day.getHours() //..get the hour
if(x>=8.30 && x<17) {
document.write('<style type="text/css">#live{display:block}"></style>')
} else
if(x>=17 && x<8.30) {
document.write('<style type="text/css">#live{display:none}"></style>')
};
</script>
Do think this is good js plus not sure if using 8.30 would work plus not sure if the last ";" is needed.
Any help on this would be great thanks.
Im now trying this code but does not work
<script type="text/javascript">
$(document).ready ( function (){
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 1600 && hour <= 1800) {
document.getElementById('live').style.display = "none";
}
});
</script>
Date().getHours() returns an integer. For your code to work you'd have to do something like this:
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 830 && hour <= 1700) {
document.getElementById('your_el').style.display = "none";
}
Note that you should only use this code when the DOM is ready for manipulation.
Although, is this really what you want? JavaScript's Date gets its date and time information from the users' clock. You would probably be better off handling this on the server.
getHours() returns a whole number (0 to 23). For 8:30, you will
need to check getHours() and getMinutes() accordingly.
The last semicolon does not need to be there.
getHours() only gets you the hours number, you need to get the minutes as well
try with
x=day.getHours()+ (day.getMinutes()/100);
about the ; it is not neccessary after an if, but it's good practice to put it at the end of each code line (that would be every other line)

Categories

Resources