It's time to wrap up the session with some old "cookies" and a closing function

Would like the message to only display once after clicking the "Cookies" button. Once the user accepts cookies, they should be stored on their device for a set period of time. Your assistance is greatly appreciated. :)

Below is the html and js code:

$(document).ready(function(){   
    setTimeout(function () {
        $("#cookieConsent").fadeIn(200);
     }, 4000);
    $("#closeCookieConsent, .cookieConsentOK").click(function() {
        $("#cookieConsent").fadeOut(200);
    });
x
This website is using cookies. More info. I agree!

Answer №1

Make sure to store the cookie and verify it on page load; if it's already there, no need for further action.

$(document).ready(function() {
  $('#cookieConsent').hide();
  if(getCookie('cookieAccepted') == null) {
    setTimeout(function () {
      $("#cookieConsent").fadeIn(200);
      }, 4000);
      $("#closeCookieConsent, .cookieConsentOK").click(function() {
        setCookie('cookieAccepted', 'cookieAccepted', 90);
        $("#cookieConsent").fadeOut(200);
      });
    }
});
  
function setCookie(cname, cvalue, exdays, domain) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  var cookieString = cname + "=" + cvalue + ";" + expires + ";path=/;";
  if(domain && domain != '') {
    cookieString += "domain="+domain+";"
  }
  document.cookie = cookieString;
}

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return null;
}
<div id="cookieConsent">
    <div id="closeCookieConsent">x</div>
    This website is using cookies. <a href="files/c11bg_cookie_policy.pdf" target="_blank">More info</a>. <a class="cookieConsentOK">I agree!</a>
</div>

Answer №2

By placing a cookie on the user's browser, you can track if the page has been loaded before based on the existence of the cookie. Once the user clicks on the 'x' or the 'I agree!' link, the message will no longer be displayed.

To ensure the message doesn't reappear, you can simply refresh the page.

If you wish to see the message again, you need to delete the cookie. For this purpose, I have included a button that allows you to delete the cookie and reload the page. Clicking on "Click for delete cookie" will make the cookie disappear and bring back the message.

<!DOCTYPE html>

    <head>
    <title>Stack Overflow</title>
    <body onload="checkBtn()">

    <div id="cookieConsent" style="display:none">
        <div id="closeCookieConsent" onClick=javascript:addBtn();>x</div>
        This website is using cookies. <a href="files/c11bg_cookie_policy.pdf" target="_blank">More info</a>. <a href="#" onClick=javascript:addBtn(); class="cookieConsentOK">I agree!</a>
    </div>
    <br/>
    <br/>
    <br/>
    <br/>
    <div id=btnHolder ><input type="button" onClick=javascript:delCookie("btn"); value="Click for delete cookie" /></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    
    function addBtn(){
        if(getCookie("btn"))
            document.getElementById('cookieConsent').style.display = 'none'; 
        document.getElementById('cookieConsent').style.display = 'none'; 
        setCookie("btn",true,5);
      }
    function checkBtn(){
        if(!getCookie("btn"))
            document.getElementById('cookieConsent').style.display = ''; 
      }
    function setCookie(cname,cvalue,exdays) {
                  var d = new Date();
                  d.setTime(d.getTime() + (exdays*24*60*60*1000));
                  var expires = "expires=" + d.toGMTString();
                  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
              }
    function  getCookie(cname){
                return (document.cookie.match('(^|; )'+ cname +'=([^;]*)')||0)[2]
            }
    function  delCookie(cname) {
            document.cookie = cname+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
            window.location.reload();
        }

    </script>
    </body>

I had to comment out the jQuery part as it was causing an error.

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

Problem with Safari: File downloaded with name "Unknown" due to Javascript issue

After successfully converting my data to text/csv, I can easily download the file in Chrome. However, when attempting to do so in Safari on an iPad or Mac, it opens a tab with the name "unknown" or "Untitled". The code snippet I am using for this is as fol ...

Enhance the performance of React code by refactoring it

Having recently started coding in React for a new organization, I find that the code in my component has grown lengthy and the submithandler method is causing multiple array iterations. Is there a way to refactor the code for better performance? The data t ...

The custom validation in Node.js using Express-Validator is ineffective

I have implemented custom validators using express-validator to include specific validations: middlewares.js module.exports = function (app) { console.log('making sure I am being called'); return function (request, response, next) { ...

Retrieving Files using Ajax Across Different File Types

I recently came across the following code snippet: DOM_imgDir = "img/UI/DOM/"; fileextension = ".jpg"; $.ajax({ url: DOM_imgDir, success: function (data) { $(data).find("a:contains(" + fileextension + ")").each(function () { filename = thi ...

What exactly is the purpose of the QueryString function and how does it work

I recently took on the role of editor for a website that I did not create. One of the webpages contains a map feature, and I've been tasked with changing how the map loads initially on the webpage. As I review the JavaScript code, I'm unsure if ...

Ways to extract pertinent information from a PHP API

I've been attempting to add parameters to my query, but I keep getting inconsistent results. Despite trying different methods, I haven't been successful. Take a look at the code below. First, here is my code that functions properly without using ...

What could be causing my tabs (such as HOME, ABOUT ME..) not displaying the correct paragraph or section content?

I have set up navigation tabs on my website using anchor tags, but they are currently not linked to any specific paragraphs. I want the corresponding paragraph to be displayed when a tab is clicked, but I'm unsure how to add this functionality using j ...

If a user enters an incorrect path, the goal is to automatically redirect them to the homepage while displaying the correct URL in AngularJS

When the URL is manually edited, the webpage displays the same content with a different URL structure. For instance, http://www.example.com/# and http://www.example.com/#/abc both show identical content. I would like to implement a redirect for any edite ...

Utilizing AJAX to submit a combination of text fields and files in an HTML form

Just starting out with AJAX and JQuery, I'm curious if it's possible to send data from an HTML form, including a text file and two separate text boxes, via an AJAX request. So far, I've managed to send the data from the text boxes but not th ...

Tips on altering the color of a circle's radius within Google Maps

I'm trying to add a circular radius on a Google Map. Even after reviewing the Google Maps API documentation, I'm still unsure of how to accomplish this task. Below is the code snippet I have been working with: const MyMapComponent = compose( ...

Can you provide an alternative code to access an element with the id of 'something' using vanilla JavaScript instead of jQuery's $('#something') syntax

Why am I seeing different console output for $('#list') and document.getElementById("list")? Here is the console printout: console.log($('#list')); console.log(document.getElementById("list")); However, the actual output in the cons ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

Receive a response in fragments from express on the browser

As I work on creating a progress bar to track long-running server-side tasks that may take up to a few minutes, I am exploring different methods to display the progress of each task. While WebSockets and interval polling are options, I prefer using long-po ...

Creating a JavaScript file to incorporate into an HTML document

I stumbled upon this code snippet here This code allows me to fetch data from a php file and insert it into a div using jQuery. While the tutorial works perfectly, I'm planning to use this for about 9-10 different links and thought of consolidating a ...

Leveraging the power of ReactJS for efficiency in executing multiple API calls concurrently

I'm encountering an issue with the following code snippet: let tmpContributors = [...this.state.contributors]; for (let i = 0; i < 10; i++) {//10 most active contributors due to performance and github limits contributorPropertiesPromises.pus ...

What is the method for including an inner wrapper around an element in Angular?

Is there a way to create an Angular directive that adds an inner wrapper to a DOM element without replacing the inner content? I have tried implementing one, but it seems to be replacing instead of wrapping the content. (view example) Here is the HTML sni ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

Best practices for correctly parsing a date in UTC format using the date-fns library

My log file contains timestamps in a non-ISO format: 2020-12-03 08:30:00 2020-12-03 08:40:00 ... The timestamps are in UTC, as per the log provider's documentation. I am attempting to parse them using date-fns: const toParse = "2020-12-03 08:40 ...

Tool to insert content into the initial subdirectory

My goal is to develop a bookmarklet that can add text after the main domain but before any subpath. For example: http://example.com/home/start -> http://example.com/text/home/start I am considering storing the full path, removing the domain, replacing ...

Align content distributed evenly will not display a division

I am currently using React to code and learning by doing so. I have two different images displayed, each followed by a div element with a height of 20px and a brown background color. I have set the height to "100%" and justifyContent to "space-between", bu ...