EU directive on cookies: What is the best way to store your preferences?

While there are numerous third-party solutions available to comply with the cookie EU directive, I prefer to learn how to implement it myself. My specific requirement is that when a user clicks on "Accept", their choice should be remembered for the entire browsing session rather than showing up every time the page is refreshed. Any guidance on achieving this would be greatly appreciated. Thanks!

// Script to display and hide cookie message
$(document).ready(function(){
      
      $(".cookie").toggleClass("cookieDisplayed");
      
      // Function to hide cookie message upon clicking "Accept"
      $(".acceptCookies").on("click", function(){
        $(".cookie").removeClass("cookieDisplayed");
        
      });
  });
.cookie {
  padding:20px;
  font-size:80%;
  width:100%;
  height:150px;
  background:#F55D2D;
  color:white;
  position:relative;
  top:-150px;
  
  transition: top 1.5s;
  -webkit-transition: top 1.5s;
  -moz-transition: top 1.5s;
}

.cookie button{
  margin-left:20px;
  position:relative;
  left:100px;
  background:white;
  color:#F55D2D;
  border: 0;
  border-radius:4px;
}

.cookie button:hover {
  background:#F89576;
  color:white;
}

.cookie button a {
  text-decoration:none;
  color:#F55D2D;
}

.cookie.cookieDisplayed {
  
  top:0;
}
<html>
  <header>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
  </header>
  <body>
     <div class="cookie">
       <p>We are using cookies to give you the best experience on our site. Cookies are files stored in your browser and are used by most websites to help personalize your web experience.</p>
       <p>By continuing to use our website without changing the settings, you are agreeing to our use of cookies.</p>
       <button><a href="aboutus.html">More information</a></button>
       <button class="acceptCookies">Accept</button>
     </div>
  </body>
</html>

Answer №1

Don't expect your javascript modifications to stick around after a reload

Surprisingly, the most effective way to address this issue is by using a cookie.

Apologies for my attempt at cleverness with the whole "it takes a cookie to acknowledge a cookie."

If you're looking for the right solution, look no further than localStorage. Both cookies and localStorage serve similar purposes of storing information on the user's device, ensuring that they have accepted the cookie notice in this scenario. However, there are differences between the two - cookies primarily communicate with the server while localStorage is more geared towards client-side communication. In this case, either method could work, but localStorage would be the simpler option.

Keep in mind that sessionStorage only retains data until the user closes their browser.

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

jquery - adjust floating section height

I designed a page with two distinct sides. On the right side, I have implemented a floating section using Bootstrap panels that can be dragged to different sections on that side. However, I am facing an issue where the height of the right side section doe ...

The flex-basis property seems to be malfunctioning as the image suddenly vanishes when

While my question may seem similar to others, the issue at hand is actually quite different. Here's how it appears in Chrome https://i.sstatic.net/tngvr.jpg Safari https://i.sstatic.net/eE74k.png In Safari, you'll notice that the map disappear ...

Navigating the use of a jQuery slider in Django has raised questions about the location of jQuery UI images

My Django application stores all media files in a designated media folder. MEDIA_URL = '/site_media/' MEDIA_ROOT = '/home/me/django/myapp/media/' ... (r'^site_media/(?P<path>.*)$','django.views.static.serve',{ ...

What makes the nav class different from the navbar class in Bootstrap?

Recently, I delved into learning about bootstrap and web development. To my surprise, I stumbled upon the nav and navbar classes in bootstrap 4. I'm curious to know what sets them apart from each other and when it's best to use one over the other ...

Having difficulties updating a value in Angular through a function written in HTML- it refuses to update

<select ng-model="currentTimeStartHour" style="width: 33%" ng-change="UpdateTime(this)"> <option ng-repeat="hour in choices" value="{{hour.id}}">{{hour.name}}</option> </select> Somewhere else on the page... {{totalHours}} Whe ...

The element 'Listitem' is unrecognized and cannot be found in the current context

I am currently working on an ASPX project in Visual Studio and have encountered an issue with a Drop Down field. It appears that the List Items are being ignored in my code. Can anyone advise me on what might be missing? <form runat="server"> &l ...

Event in Bootstrap modal fails to activate

I've been attempting to link some code to execute when my modal is opened. Despite successfully opening the modal, I am puzzled as to why my event fails to trigger. Below is the structure of my modal: <div id="details" class="modal fade" style="d ...

Does the user need to download the scripts from Google API multiple times during the insertion process?

Concerned about the potential need for multiple downloads of a script from an unknown location on the user's computer, I would like to explore options to mitigate this issue. Specifically, I am considering creating a condition to check the download st ...

What causes the code following the </html> tag to be shifted in front of the </body> tag? Is there a noticeable improvement in performance

After exploring various Stack Overflow posts like this particular SO question, I came across an unconventional Google recommendation on CSS optimization. This recommendation suggested deferring CSS loading with markup that looked like this: <d ...

Use VB.NET to dynamically update cell content in HTML

Can you assist me with updating cellContent in HTML using vb.net? The DataGrid view is on a website. Below is the inspected HTML: <div class="grid-controls"> <form method="post" class="vss-app-form grid-control-popover none" id="gridMorePopov ...

What is the best way to create a JQuery function that fills a div based on the selected option from an HTML select

Check out this simple JavaScript function below. <html> <head> <script> $(document).ready(function() { $.get('getImage.php', function(data) { $('#imageSelector').html("<select>" + d ...

What steps can be taken to implement a code generation feature on our website?

I need to provide the HTML code of my order form to third parties. After they register and pay, they should be able to copy and paste the HTML code from my site onto their own site. The date will then be saved on my site with a reference to the reseller. ...

What is the reason for the presence of white space surrounding the div element

In the td element, I have four nested div elements. However, there seems to be a small margin or space created between them that I cannot figure out how to remove. If this spacing is due to the behavior of the inline-block, then how can I override it? ...

Leveraging jQuery and Ajax for retrieving information from a JSON document

As a newcomer to JS, I have successfully set up a JSON file on my Express server. My code snippet looks like this: const data = require('./src/data.json') app.get('/search', function (req, res) { res.header("Content-Type",'app ...

eliminating list item from unordered list depending on the input of either first or last name

My objective is to refine a lengthy list as the user types in a search for a specific person by first or last name. The current code I have functions adequately, but encounters an issue when there is a space in the input field. My goal is to allow users to ...

Resetting the value of a radio button input option to null using Angular2 ngModel

In my Angular2 application, I am attempting to implement radio button inputs using ngModel and value. The goal is to have three options: true, false, and null. However, I am struggling to assign a value of null to one of the inputs. Ideally, when nothing ...

Is there a way to use jQuery and regex to obtain a unique radio attribute name based on its ID?

Here are some input elements I have: <input name="option[100]" value="first" type="radio" checked="checked"/> <input name="option[100]" value="second" type="radio" /> <input name="option[100]" value="third" type="radio"/> I can use ...

When the user saves the changes on the pop-up window, the main window will automatically refresh

I currently have a calendar feature that allows users to create, edit, and delete appointments. When a user clicks on the new appointment button, it opens a window above the calendar interface. Once the user fills out the necessary fields and clicks save, ...

Looking for a way to exclude both parents and children from a list of relatives? Want to ensure that the

I've been struggling to align these list elements with their counterparts, but they seem to automatically create a margin for their child elements. It is essential for these list items to maintain the position:relative attribute so that the #dropdown ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...