The cookie message will only be displayed once after clicking the submit button

Can someone assist me with setting up a cookies message popup? I want the message to only display once per user click on accept. Here is the code snippet: https://jsfiddle.net/bz8ur3wu/1/

$(document).ready(function(){
    $("button").click(function(){
        $(".cookie").fadeOut();
    });
});
.cookie{width:100%;padding:20px;background:rgb(231, 231, 231);bottom:0;left:0;position:fixed;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cookie">
    This website uses cookies. 
    <button>accept</button>
</div>

Answer №1

If you're searching for an alternative approach, consider utilizing the localStorage method. Check for a saved value named cookieconsent and apply a class to the body element if it exists. Otherwise, set the value when the user interacts with the button.

$(document).ready(function(){
    if (!!localStorage.getItem("cookieconsent")) {
        document.body.classList.add("cookieconsent")
    } 
    else {
        $("button").click(function() {
            localStorage.setItem("cookieconsent", "ok")
            $(".cookie").fadeOut();
        });
    }
});

Next, in your CSS, display the .cookie element only if the user has not previously accepted by checking if the body does not have the .cookieconsent class.

.cookie { 
    display: none; }

body:not(.cookieconsent) .cookie {
    display: block;
}

Answer №2

I came up with a nifty little script that I now include in all of my projects. It handles the creation of a cookie, checks if it exists or not, and then either shows or hides a specific div with the id #cookie-notice.

I believe this is a solid starting point, and you can customize it as needed.

var myProj = myProj || {}
myProj.cookiePolicy = function (__M) {
    var cookiePolicy = document.querySelector('#cookie-notice'),
        acceptCookieBtn = cookiePolicy.querySelector('#cn-accept-cookie'),
        closeCookiePolicy = cookiePolicy.querySelector('a.close-button');

    closeCookiePolicy.addEventListener('click', function (ev) {
        ev.preventDefault();
        acceptCookie();
    });

    document.querySelector('body').addEventListener('click', function (ev) {
        acceptCookie();
    });

    window.addEventListener('scroll', function (ev) {
        acceptCookie();
    });

    acceptCookieBtn.addEventListener('click', function (ev) {
        ev.preventDefault();
        acceptCookie();
    });

    if (document.cookie.indexOf('cookie_notice_accepted') === -1) {
        cookiePolicy.classList.add('show');
    }

    function acceptCookie() {
        if (document.cookie.indexOf('cookie_notice_accepted') === -1) {
            cookiePolicy.classList.add('show');
            // set cookie
            var d = new Date();
            d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
            document.cookie = 'cookie_notice_accepted=true' + ';expires=' + d.toGMTString();
        }

        if(cookiePolicy){
            cookiePolicy.parentNode.removeChild(cookiePolicy);
            cookiePolicy = null;
        }
    }
}(myProj);

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

Encountering a mismatched anonymous define() error when using RequireJS in conjunction with Algolia Docsearch

Incorporating Algolia Docsearch with MadCap Flare has been my current challenge. MadCap Flare, a technical documentation tool that generates HTML output, is proving to be tricky when it comes to integrating the Docsearch feature. While the underlying crawl ...

Ensure the left column extends all the way down

I've been struggling with this issue for almost three days now. After reading numerous articles on creating a three-column layout and experimenting with absolute and relative positioning, I'm still not able to achieve the desired result. What I& ...

When making updates to the HTML code, the cursor unexpectedly moves to the beginning of the code tag

Whenever I try to type in the code box and the content updates with the script provided, my cursor keeps getting moved to the beginning of the code. What can I do to resolve this issue? function MaintainCursorPosition(Control) { var target = $(&apo ...

jQuery does not support the addition of new fields in HTML

Recently, I've been working on creating a lucky number generator. Initially, I developed it using C# and now I'm in the process of transitioning it to JavaScript and jQuery. You can view the latest version here. However, I've encountered an ...

Positioning an absolute element inside a relative parent with a defined maximum width

I am attempting to position #header-supporter at the bottom right of #header-image, with overlapping elements. The challenge lies in setting a max-width of 1280px on #header-supporter-cont to maintain consistency with the site's margins. I have tried ...

Using a function on a singular element

I'm currently working on my portfolio and I would like to organize my projects in a menu similar to this felipestoker.com When you click on Works, it displays a menu with my projects categorized. However, when I click on a category, all of them appea ...

The JQuery loading symbol does not prevent keyboard interactions

I successfully implemented a Jquery busy indicator in my application using the following link: However, I noticed that even though it prevents users from clicking on input elements while loading, I can still navigate to these elements by pressing the tab ...

Node was experiencing difficulty locating a module alias that had been defined in the tsconfig file and package.json

I'm currently working on deploying a typescript project in production mode. You can find the code on Github here Executing npm run start:dev launches the server at http://localhost:3000/ Running npm run build generates the dist folder The definitio ...

Step-by-step guide for creating the correct .css for Html.TextBoxFor

When it comes to my design preferences, I always aim for textboxes with a proper style. For instance: @Html.TextBoxFor(m => m.Number, new {disabled = "disabled", @class = "special-container"}) And in the .css file: .special-container { backgroun ...

Filestack - NoCrop: Utilize whitespace to maintain the square aspect ratio when uploading images without cropping

Is there a way to use Filestack to upload an image and automatically add whitespace to the sides of the image in order to keep it square without cropping? click here for image ...

What steps should I take to design a mobile-friendly navigation bar?

I have shared the code for my navigation bar in a previous post Fixing Nav Bar to top of page. Now, I want to create a mobile version of it, but I am new to designing for mobile devices. Based on feedback and some CSS tweaking, I have managed to make it wo ...

Tracking the referral source when the email box is clicked

document.referrer is a JavaScript method that returns the URI of the page that linked to the current page. If the user navigated directly to the page, for example through a bookmark, the value returned by document.referrer will be an empty string. You can ...

Is it allowed to use any AngularJS directives within other directives?

I am trying to create a directive that will display a list of objects from my controller. Inside this directive, I want to be able to use one of several possible sub-directives, but the specific one to be used may vary. If I set the sub-directive name in t ...

Displaying an error in Ajax caused by PHP

I've been attempting to send a POST request to a URL using Ajax. Here's what my JS/JQuery code looks like: var params = { 'username' : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="781d1c1c190a1c ...

Show text and image side by side on the same row

I am looking to showcase both image and text on the same line, similar to how it's done on tripadvisor.in/ <div style="display:inline-block"> <div style="display:inline;float:left"> <a href="CollegeProfile.php" class="white"> <h ...

What is the functionality of Google Chrome's "New Tab" iframes?

Have you ever wondered about those 8 small iframes displaying your most visited websites? How do they capture snapshots of the websites? How are the websites chosen for display? And most importantly, how do they actually work? Edit: I want to learn how to ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

How to Retrieve Correct JSON Data from Mongoose Query in Node.js

I am currently working on an express application that utilizes mongoDB as the database and handlebars as my server-side templating engine. Unlike many applications, I have chosen not to incorporate AngularJS or Ajax into my project. One of the challenges ...

Setting a default value in a multi-select dropdown using react-select

I have taken over management of my first React app, and I am facing a seemingly simple change that needs to be made. The modification involves an email signup page where users can select their interests from a multi-select dropdown menu. My task is to mak ...

What is the process for implementing THREE.EdgesGeometry on a model imported using THREE.OBJLoader?

I have been attempting multiple times to add edges in a model loader using the OBJLoader, but I am unable to achieve it. Mloader = new THREE.MTLLoader(); Mloader.setPath( dir ); Mloader.load( mtl_dir, function ( materials ) { ...