Change CSS background color in jQuery on timer

时间:2018-07-24 10:07:10

标签: javascript jquery wordpress countdowntimer

I have to create a function in JQuery on the timer from the plugin wordpress Quiz and survey Master.

As long as the timer hasn't passed 45 minutes it's displayed in green but when it exceeds it must be displayed in red (for information the timer is a countdown timer and predifined on 3 hours at the moment).

in my research i know I have to use the css function like this

$('div.mlw_qmn_timer').css("background-color": "green");
$('div.mlw_qmn_timer').css("background-color": "red");

so I haven't any idea how I can get the 45 minutes to change the background on the beginning of the 3 hours.

1 个答案:

答案 0 :(得分:4)

You can use setTimeout to change the color after 45 minutes.

// Initially, set the background as green
$('div.mlw_qmn_timer').css("background-color", "green");

var interval = 45 * 60 * 1000; // `setTimeout` accepts time in millis

// Change the color to red after 45 minutes    
setTimeout(function() {
  $('div.mlw_qmn_timer').css("background-color", "red");
}, interval);

Following is a demo which does the exact thing, but with an interval of 10 seconds:

// Initially, set the background as green
$('div.mlw_qmn_timer').css("background-color", "green");

var interval = 10000; // `setTimeout` accepts time in millis

// Change the color to red after 10 seconds
setTimeout(function() {
  $('div.mlw_qmn_timer').css("background-color", "red");
}, interval);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mlw_qmn_timer">test</div>