I have a database and I store there a text, its duration and time when it should appear on the webpage.
The result of the php is as follows:
{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:15"},{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:30"},{"text_content":"gdsgdsgds","text_duration":"15","start_time":"2015-10-01 14:00:00"}
I have a jquery script that fetches the data from the database and prints it on the screen:
var results =[];
var cursor = 0;
function myFunction () {
$.getJSON('list2.php', function(json) {
results = json;
cursor = 0;
// Now start printing
printNext();
});
}
function printNext(){
if(cursor == results.length){
// Reset the cursor back to the beginning.
cursor = 0;
}
// Print the key1 in the div.
//$('#mydiv').html(results[cursor].key1);
$('#mydiv').hide('fast', function(){ $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); });
// Set a delay for the current item to stay
// Delay is key2 * 1000 seconds
setTimeout(function(){
printNext();
}, results[cursor].text_duration * 1000);
// Advance the cursor.
cursor++;
}
and now I wanted to add a feature that text displays on the screen only on a date that is fetched from database, as start_time
, but I'm not sure if it's possible to do on jquery only, without any further access to the server code..
I tried adding some if statement like:
if(results[cursor].start_time == new Date()){
just before printing it on the screen but it didn't do the trick. Could you help me with that? Thanks!
Parse your json string with JSON.parse
:
var myObj = JSON.parse(results[0]);
and compare your start_time
:
if (new Date(myObj.start_time) == new Date())
if you want run your function on specific time use setTimeout:
var diff = new Date(myObj.start_time).getTime() - new Date().getTime();
setTimeout(function() {
$('#mydiv').hide('fast', function() {
$('#mydiv').html(results[cursor].text_content);
$('#mydiv').show('fast');
});
}, diff)
or you can execute your function every 1000ms by using setInterval
and stop it with clearInterval
:
function check() {
if (new Date(myObj.start_time) == new Date()) {
$('#mydiv').hide('fast', function() {
$('#mydiv').html(results[cursor].text_content);
$('#mydiv').show('fast');
});
clearInterval(myInterval);
}
}
var myInterval = setInterval(check, 1000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With