JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css">
<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">
<img src="..." class="rounded me-2" alt="...">
<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">
${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));
}
}, 1000);
}
// Handle button click for buttons with the class 'toasted'
$('.toasted').on('click', function() {
var btn = $(this);
var btnId = btn.attr('id');
var interval = 15 * 1000; // 15 seconds interval
var endTime = new Date().getTime() + interval;
// Disable the button
...