John Beasley John Beasley - 1 year ago 126
HTML Question

jquery show and/or hide element based on set date

I believe this one is a logic error.

Trying to show a button called 'oecard' when a saved start time has been reached, and then hide it once the saved end time has been reached.

var db_st = item.DB_ST; // saved in db as '2017-10-02 12:20:00 PM'
var db_et = item.DB_ET; // saved in db as '2017-10-02 12:25:00 PM'

var cd_start = new Date(db_st).getTime(); // converts db date to milliseconds
var cd_end = new Date(db_et).getTime(); // converts db date to milliseconds

var currentdate = $.now();

var loop = setInterval(function(){
if(currentdate >= cd_start && currentdate <= cd_end)
{
$('#oecard').show();
}
else
{
$('#oecard').hide();
}
},1);


I attempted the above code to no avail. The button does not appear on the saved time, but when I refresh the page, it does. Same thing happens with the end time.

I know this has to be some kind of logic error. I need to do this dynamically without having to refresh the page.

Please help and thank you.

Answer Source

You need to put currentdate inside your loop:

var loop = setInterval(function(){
  var currentdate = $.now();

  if(currentdate >= cd_start && currentdate <= cd_end) 
  {
    $('#oecard').show();
  }
  else
  {
    $('#oecard').hide();
  }
},1);

The value returned by $.now() is not dynamic, it will not update for you, you'll need to call it every time your setInterval callback is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download