Conceal Bootstrap Toast for a day following dismissal

I have implemented Bootstrap 5 toasts to showcase an advertisement on my website. The goal is to make the advertisement disappear for 24 hours once the user closes it.

Here's the current code snippet:

<div class="position-sticky bottom-0" style="z-index: 5">
    <div class="toast hide text-center text-white bg-primary border-0" id="cbAd" role="alert" aria-live="assertive" aria-atomic="true" style="width: 100%; border-radius: 0;">
        <div class="toast-header">
            <strong class="me-auto">Ad</strong>
            <small>Website.com</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body" style="transform: rotate(0);">
        This is the advertisement text.
        <div class="mt-1"><a class="btn btn-success stretched-link" href="">Buy Something</a></div>
        </div>
    </div>
</div>

Javascript:

var option = {
    animation: true,
    autohide: false
};
function cbToast( ) {
    var toastElementHTML = document.getElementById( 'cbAd' );
    var toastElement = new bootstrap.Toast( toastElementHTML, option );

    toastElement.show();
}
setTimeout(cbToast, 5000);

Is there a way to achieve this using local storage?

Answer №1

<button onclick="closeAdvertisement()" type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
function closeAdvertisement() {
    document.getElementById( 'cbAd' ).style.display = "none";
    let expirationTime = new Date();
    expirationTime.setDate(expirationTime.getDate() + 1);
    localStorage.setItem("close_expire_time", expirationTime.getTime());
    // Note: getTime() converts it back to Unix time
}

function cbToast() {
    // ... your code
    if (isShowAdvertisement()) toastElement.show();

    function isShowAdvertisement() {
        const expireTime = localStorage.getItem("close_expire_time"),
            currentTime = new Date().getTime();
        
        // Easy-to-read version
        if (!expireTime) {
            return true; // does not exist
        } else {
            if (expireTime - currentTime > 0) {
                console.log(`${expireTime - currentTime}ms before expiration`);
                return false; // not expired yet
            } else {
                return true; // expired
            }
        }

        // Short version
        return !expireTime ? true : ((expireTime - currentTime > 0) ? false : true);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while trying to connect to MongoDB: MongooseServerSelectionError

I am encountering an issue while attempting to establish a connection from my Node.js application to MongoDB using Mongoose. Every time I try to launch the application, I encounter the following error: "Error connecting to MongoDB: MongooseServerSele ...

Tips on how to update the page and create a counter for a table view

I am working with an HTMLB Tableview where I need to regularly update its firstRowVisible property every 3 minutes with a dynamic value. For example, if it starts at zero, after 3 minutes it should be set to 21 and continue increasing by a certain interval ...

Stepping up Your Next.js Game with the Razorpay Payment Button Integration

When using the Razorpay payment button on a website, it provides a code snippet like this: <form> <script src = "https://cdn.razorpay.com/static/widget/payment-button.js" data-payment_button_id = "pl_FNmjTJSGXBYIfp" data ...

Creating a Gmail share button in AngularJS: A step-by-step guide

I created a messaging web application using AngularJS, and I successfully added functionality to share messages via email using the "mailto" link. However, this method only works if the user has an email client installed. Now, I am looking for a solution ...

Uncovering the secrets to fetching numerous JSON files asynchronously using JavaScript and JQuery

My goal is to fetch multiple JSON files using JavaScript or jQuery and extract elements named j_name, j_value, and j_sts into sarr[i], rarr[i], and parr[i], respectively. var sarr = new Object; var rarr = new Object; var parr = new Object; //num_json rep ...

Remove and modify an li element that has been dynamically generated within a ul list

Currently, I am facing an issue in my code. I am dynamically creating li elements by taking input from an input box and then appending the data within li tags using jQuery. However, after adding the li element, I have included a delete button. The problem ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Displaying tooltips dynamically for newly added elements all sharing a common class in React

I'm facing an issue with the primereact tooltip component from . Everything seems to be working fine except for the target property. When I have multiple elements on a page with the same class, the tooltip works as expected. However, when I add a new ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

Confirm the object received from the API and assign default values

Seeking to extract data from an API and verify if all fields are strings, but if they are missing I aim to assign default values. My intention was to utilize the yup library to validate the object accordingly, ensuring that the returned function is prope ...

Using expressJS and MongoDB to create a secure login and registration system

I am interested in adding a login/register function to my expressJS API. Currently, I am only inserting the password and email into my database. I would like this function to first check if a user with this email is already in the database - if yes, then s ...

When utilizing exit-hook with process.on('SIGTERM'), child_process spawn requires two control-c commands to exit properly

I have the following program running: const { spawn } = require("child_process"); const exitHook = require("exit-hook"); exitHook(() => { console.log("Leaving"); }); spawn("my-program", ["my-args"], { stdio: "inherit" }); // Long running server ...

Contrast between PHP and JavaScript output texts

Hey everyone, I'm dealing with a bit of an awkward situation here. I am trying to return a string variable from PHP to JavaScript and use it for a simple comparison in my code. However, the results are not turning out as expected. Initially, I send a ...

Fix issue with nested form in Rails 3.0.9 where remove_fields and add field link functionalities are not functioning properly

I've been watching Ryan Bates' nested_forms episodes 1 & 2 on RailsCasts, successfully implementing the functionality in one project without any issues. However, in a new project using the same reference, the remove and add field functionalit ...

What is the best way to organize a data tree in JavaScript for easy parsing on the frontend?

I'm struggling with a unique tree data structure in my code. Each node is represented by an object, and I need to transfer the entire tree to the front-end. Unfortunately, JavaScript's limitation on using objects as keys prevents me from implemen ...

Resolved plugin issue through CSS adjustments

Take a look at this template 1) After referring to the above template, I developed a fixed plugin using JavaScript. 2) Clicking the icon will trigger the opening of a card. 3) Within the card, I designed a form using mdb bootstrap. Everything seems to ...

Guide for utilizing a table value as a parameter in a mySQL query with PHP

My website features an HTML table that is filled with data pulled from a mySQL table using PHP. Each row in the table is clickable, and when clicked, it opens a modal that contains a form to update and submit data back to the database using a mysql update ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...

Dynamic banner featuring animated text, automatically resizing divs based on width while maintaining body width

Currently, I am working on creating a banner with moving text. While I have managed to come up with a solution for implementing this effect, there are two significant issues that I am facing. The width values in pixels need to be manually adjusted based ...

I am sometimes experiencing issues with activating ajax code using Bootstrap 3 modal

I'm stumped trying to find a solution for this issue. Currently, I am utilizing the bootstrap modal to retrieve ajax content from a specified URL. To prevent content overlap, I am using $.removeData() when reloading the content. The problem arises w ...