Issue
How to show/hide elements depending on the current Hour?
- show 1st SPAN from 12:00 to 14:00 (Hide other spans)
- show 2nd SPAN from 17:00 to 03:00 (Hide other spans)
- show 3rd SPAN from 07:00 to 10:00 (Hide other spans)
Attempt
var pagi = new Date(); // morning
var siang = new Date(); // day
var malam = new Date(); // night
var time = new Date().getTime();
if (time > pagi.setHours(12, 00)) && time < end.setHours(14, 00)) {
document.getElementById("malam").style.display = "block";
document.getElementById("pagi").style.display = "none";
document.getElementById("siang").style.display = "none";
} else if (time > siang.setHours(17, 00) && time < end.setHours(03, 00))) {
document.getElementById("malam").style.display = "none";
document.getElementById("pagi").style.display = "block";
document.getElementById("siang").style.display = "none";
} else if (time > malam.setHours(07, 00)) && time < end.setHours(10, 00)) {
document.getElementById("malam").style.display = "none";
document.getElementById("pagi").style.display = "none";
document.getElementById("siang").style.display = "block";
}
<span id="malam" style="background-color:magenta;"> malam </span>
<br/>
<span id="pagi" style="background-color:cyan;"> pagi </span>
<br/>
<span id="siang" style="background-color:orange;"> siang </span>
Solution
You can use getHours()
to the get the local hour and then use conditional statements to display elements accordingly.
let malam = document.getElementById("malam"),
pagi = document.getElementById("pagi"),
siang = document.getElementById("siang"),
today, h;
function show(){
today = new Date(),h = today.getHours();
if(h >= 3){
if(h>=7 && h<10){
malam.style.display = 'none';
pagi.style.display = 'none';
siang.style.display = 'block';
}
else if(h>= 12 && h<14){
malam.style.display = 'block';
pagi.style.display = 'none';
siang.style.display = 'none';
}
else if(h>=17){
malam.style.display = 'none';
pagi.style.display = 'block';
siang.style.display = 'none';
}
}else{
malam.style.display = 'none';
pagi.style.display = 'block';
siang.style.display = 'none';
}
}
<p id="malam" style="background-color:magenta; display:none"> malam </p>
<p id="pagi" style="background-color:cyan; display:none"> pagi </p>
<p id="siang" style="background-color:orange; display:none"> siang </p>
<button onclick='show()'>test</button>
Note: to use inline event-handling is not the best practice, if you would like to improve this code use object.onclick = function(){myScript};
You can read more here
Answered By - Gass
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.