twnt22 twnt22 - 7 months ago 25
PHP Question

Show div when variable (time) is 0

I'm trying to show div when time (importing from database) - current time will be 0. How to do that? Here's the code:

while ($row = mysqli_fetch_array($result)) {
echo "<div class='alert' id='" . $row['id'] . "' style='display:none'><br><br><center><h2>";
echo $row['title'];
echo "<br><br>";
echo $row['category'];
echo "</h2><br><br><hr><br><br></center>";
echo $row['description'];
echo "</div>";
$timeFirst = strtotime($row['date']);
$timeSecond = strtotime("now");
$differenceInSeconds = $timeFirst - $timeSecond;
if ($differenceInSeconds==0)
{
echo "<script>";
echo "$(document).ready(function(){";
echo "$('#". $row['id'] . "').show();";
echo "$('#". $row['id'] . "').delay(15000);";
echo "$('#". $row['id'] . "').hide();";
echo "});";
echo "</script>";
}
}

Answer

I think you want to add a setTimeout() to your javascript code instead of if ($differenceInSeconds==0) {} PHP side.

Also you need to rewrite your jQuery from (effectively showing an element, delaying nothing and hiding it right away)

$("#element").show();
$("#element").delay(15000);
$("#element").hide();

to

$("#element").show().delay(15000).hide(0);

Full code below.

while ($row = mysqli_fetch_array($result)) {
    echo "<div class='alert' id='" . $row['id'] . "' style='display:none'><br><br><center><h2>";
    echo $row['title'];
    echo "<br><br>";
    echo $row['category'];
    echo "</h2><br><br><hr><br><br></center>";
    echo $row['description'];
    echo "</div>";
    $timeFirst  = strtotime($row['date']);
    $timeSecond = strtotime("now");
    $differenceInSeconds = $timeFirst - $timeSecond;

    // Adding a setTimeout so your JS code actually gets written and executes when it should.
    if ($differenceInSeconds >= 0) {
        echo "<script>";
        echo "$(document).ready(function(){";
        echo "window.setTimeout(function() {";
        echo "$('#". $row['id'] . "').show().delay(15000).hide(0);";
        echo "}, " . $differenceInSeconds * 1000 . ");";
        echo "});";
        echo "</script>";
    }
}