Reputation: 25
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>
Upvotes: 0
Views: 1236
Reputation: 3532
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)
Upvotes: 0
Reputation: 26530
getHours()
returns a whole number (0 to 23). For 8:30, you will
need to check getHours()
and getMinutes()
accordingly.Upvotes: 0
Reputation: 23813
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.
Upvotes: 1