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

What is the best practice for incorporating CSS and JavaScript files into a PHP template?

I've created a basic template for my PHP website, but I'm struggling to find the best way to include my CSS and JavaScript files. Take a look at my index.php file below: <?php include'core/template.php'; $temp=new Template(); $sett ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

Using Cordova plugman to add the initial platform-specific plugin into the project

Here are the system dependencies: cordova: @7.1.0 plugman: @2.0.0 I am trying to use plugman specifically for installing plugins on a particular platform (such as android). Having reviewed the documentation, I find that the workflow and usage is not en ...

The mysterious anomaly in Vue.js

I am attempting to assign a data object named types upon receiving a response in the ready() method. This is what I have: export default { data () { return { types: null } }, ready () { TypeService.showAll(1) .then(functio ...

Error: The `queries` property is undefined and cannot be read (react.js)

Here is the code snippet I am currently working with: import { useState } from 'react' import { QueryClientProvider, QueryClient } from 'react-query' import { ReactQueryDevtools } from 'react-query-devtools' import Navba ...

useEffect runs endlessly

Currently, I am using React with hooks to handle API calls and implement autoscroll functionality on a data-heavy screen. However, I have encountered a problem where the autoscroll feature implemented through a separate useEffect is interfering with the ot ...

Dealing with a throw er; uncaught 'err' event while configuring a server with nodemon

I am currently in the process of setting up my local server using node.js and nodemon. Initially, everything runs smoothly on localhost, but as soon as I refresh the page or navigate to another page, the server crashes with an 'unhandled error event&a ...

Click to add a card

Attempting to incorporate a new row with the click of a button dynamically has proven to be challenging for me. As someone who is relatively new to JavaScript, I am struggling to figure it out. In the demonstration provided below, you will notice that noth ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

The jQuery Modal Dialog functions properly on the initial page load, but fails to work on subsequent pages unless manually refreshed

So, I've encountered an issue with my jQuery modal dialog. It's set up to remind non-registered users to sign up when they try to access user-only actions. Oddly enough, the dialog functions perfectly after a page refresh on THAT specific page. H ...

Guide to concealing List elements from the Search Filter when the search input field is emptied

I am facing a challenge with an HTML list of items. Here is the structure: <ul id="fruits"> <li><a href="#">Mango</a></li> <li><a href="#">Apple</a></li> <li><a href="#">Grape</a>& ...

Issue with using async await in map function: async function may not complete before moving on to the next item in the

Currently, I have an array that needs to be mapped. Inside the mapping function, there is an asynchronous function being called, which conducts an asynchronous request and returns a promise using request-promise. My intention was for the first item in the ...

Instead of presenting MySQL data in tables on an HTML page, showcase it in editable text boxes

I have successfully imported data from my database table into an HTML table, but now I want to display them in locked text boxes. When the user clicks an "edit" button, the corresponding text box should become unlocked so that they can edit the data and sa ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Which characters are permissible for the id attribute to prevent the jQuery selector from throwing an exception?

I am facing a situation where the id attribute is inputted by an end user. For instance, if the id for a textbox is "11_=11" as entered by the user, then the HTML code will appear like this: <input type="text" id="11_=11"> The corresponding jQuery ...

"Can you provide guidance on binding data in vue.js when there is a dash (-) in the key of the JSON

My JSON data is structured as follows: { "color-1": "#8888", "color-2": "#000" } I am attempting to bind this variable with a style tag for a Vue component. However, my current approach seems to not be functioning as expected. <div v-bind:sty ...

Activating controllers with 2 independent sliders

(Using the WordPress Slider Revolution plugin) I have set up two sliders next to each other - one displaying the service name and description, and the other showing images. The goal is for clicking a specific bullet on the service slider to also trigger t ...

Every time I attempt to execute route.js in my API folder, I encounter a persistent 404 error

Project Structure: https://i.stack.imgur.com/qMF6T.png While working on my project, I encountered an issue with a component that is supposed to call an API function. However, it seems like the file is not being found. I have double-checked the directory ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

Mongoose: When encountering a duplicate key error (E11000), consider altering the type of return message for better error handling

When trying to insert a duplicate key in the collection, an error message similar to E11000 duplicate key error collection ... is returned. If one of the attributes is set as unique: true, it is possible to customize this error message like so: {error: ...