JSFiddle - React, Tailwind, and code Playground
by Russ Blanc
HTML
<!-- template begins -->
<div id="alert_template" class="alert alert-info alert-dismissable hidden">
<button type="button" class="close" data-dismiss="alert"
aria-hidden="true">
×
</button>
<p>There are <span id="jobs_count">4</span> jobs avaialble!</p>
</div>
<!-- template ends -->
<div class="alert alert-info alert-dismissable">
<button type="button" class="close" data-dismiss="alert"
aria-hidden="true">
×
</button>
<p>There are <span id="jobs_count">4</span> jobs avaialble!</p>
</div>
JavaScript
$(document).ready(function() {
var jobs_count = 0;
setInterval(function() {
// the actual code:
// $.get('notification.php', checkJobsCounter);
// notification.php returns a single number, e.g.: 10
// demo: return the number of minutes in each hour instead the job_id and jobs_count
var mock = (new Date()).getMinutes();
checkJobsCounter(mock);
}, 15000);
function checkJobsCounter(data) {
if (jobs_count !== data) {
if ($(".alert:not(.hidden)").length <= 0) { // don't show new alert if the user haven't dismissed the old one
// job_id got updated... need to show it
var $notification = $("#alert_template")
.clone()
.removeClass("hidden")
.attr("id", "") // removes id of the cloned DOM node
.appendTo("body");
}
$(".alert-dismissable span#jobs_count").text(data);
jobs_count = data;
}
if(jobs_count === 0) {
$(".alert-dismissable:not(.hidden) button").click();
}
}
});