JSFiddle - React, Tailwind, and code Playground
HTML
<button type="button" id="test_1" class="toasted btn btn-sm btn-success">Test 1</button>
<div class="toast-container"></div>
JavaScript
// Function to update toast dynamically
function updateToast(btnId, endTime) {
var remainingTime = endTime - new Date().getTime();
var countdownId = 'countdown_' + btnId;
var toastId = 'toast_' + btnId;
var toastContent = `
<div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-bs-autohide="false">
<div class="toast-header">
<strong class="me-auto">Bootstrap</strong>
<small id="${countdownId}" class="text-body-secondary"></small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
${Math.floor(remainingTime / 1000)} seconds left for button with ID: ${btnId}
</div>
</div>`;
// Append toast to the container
$('.toast-container').append(toastContent);
// Show the toast
$('#' + toastId).toast('show');
// Update countdown every second
var intervalId = setInterval(function() {
var remainingTime = endTime - new Date().getTime();
if (remainingTime > 0) {
$('#' + countdownId).text(Math.floor(remainingTime / 1000) + ' seconds left');
} else {
clearInterval(intervalId);
$('#' + toastId).toast('hide');
// Re-enable the button if endTime is expired
$('#' + btnId).prop('disabled', false);
// Remove button ID from localStorage if endTime is expired
localStorage.removeItem('endTime_' + btnId);
var btnIdsArr = JSON.parse(localStorage.getItem('btnIDS')) || [];
btnIdsArr = btnIdsArr.filter(id => id !== btnId);
localStorage.setItem('btnIDS', JSON.stringify(btnIdsArr));
}
}, 100);
}
// Function to recreate toasts on page load
function recreateToasts() {
var btnIdsArr = JSON.parse(localStorage.getItem('btnIDS')) || [];
var currentTimeMillis = Date.now(); // Get current time in milliseconds
btnIdsArr.forEach(function(btnId) {
var endTime = localStorage.getItem('endTime_' + btnId);
// Check if...