1

I need to highlight text at a specific time.

<style>
.highlight { 
background-color:#FFFF00; 
}
</style>
<span class="timer">Hello World</span>
<script> 
var date = new Date();
var minute = date.getMinutes();
var hour = date.getHours();


if(
        (hour >= 9 && minute >= 59) &&
        (hour <= 10 && minute <= 59)
    ){
           $('timer').addClass('highlight');
    }
</script>

In the above example, it should highlight "Hello World" between 10:00 and 11:00. This isn't working - any thoughts?

Chris Hamilton
  • 555
  • 5
  • 22
Mezz
  • 95
  • 1
  • 1
  • 5
  • you need to reload a page after specific x seconds to get to know when time is your specified than change color.http://stackoverflow.com/questions/1217929/how-to-automatically-reload-a-web-page-at-a-certain-time – Afnan Ahmad Feb 22 '17 at 14:11
  • that's true if he wants it to update in real time, but it's not the core issue - the if statement logic is faulty. See my answer below. – A. Damond Feb 22 '17 at 14:16

3 Answers3

1

Your if statement is equivalent to doing the same thing without parentheses. So you're checking to see if the hour is both greater than or equal to 9 and less than or equal to 10 (which will only be true if the hour is either 9 or 10) and also if the minute is both greater than or equal to 59 and less than or equal to 59 (which will only happen if the minute is exactly 59). So your if statement is only going to return true if your time is either 9:59 or 10:59.

Why not just use if (hour === 10)?

A. Damond
  • 152
  • 1
  • 8
1

Like A. Damond said your if statement is only true if your time is either 9:59 or 10:59.

I would change your if statement to:

var date = new Date();
var minute = date.getMinutes();
var hour = date.getHours();


if ((hour === 10)) {
  $('.timer').addClass('highlight');
}
.highlight {
  background-color: #FFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="timer">Hello World</span>

Also you have to add the right selector in your jQuery addClass call.
$('.timer') not $('timer').

EDIT I've updated the if clause

Sebastian
  • 951
  • 6
  • 21
0

it doesn't work because in the jQuery selector you have to put a 'dot'.

$('.timer').addClass('highlight');

when you want select an id, just put

$('#timer').addClass('highlight');

As @Damon has suggested, it's simpler if you just check only the hour

(=== 10 || (=== 11 && minute === 00)) // this will include also the 11:00

Of course, if final user opens the page (at 10) and he/she never updates/reloads, the background will be always visible, or the opposite, if he opens the page at 9. To do a job well done and working properly, you have to introduce a clock on the page and this can be a good example: http://www.tristanwaddington.com/2010/08/javascript-clock/

misterwolf
  • 424
  • 4
  • 14