Instructions for setting a cookie to conceal a notification bar upon the second page load

I am looking for the following scenario:

  • When a new visitor lands on my website, a notice bar fixed to the bottom of the screen becomes visible.
  • After clicking on a menu item to navigate to another page, a cookie is set upon the second page load. This cookie will ensure that the notice bar remains hidden for a period of 60 days. It is crucial that the notice bar does not flicker on page load due to the asynchronous loading of Javascript.
  • Alternatively, the user can click on the "Ok" button to close the notice bar and set the same cookie.

This is the structure of my HTML:

<div id="cookie-message">
    <span>Cookie notice will be displayed here <a href="#">Read more</a> <a href="#" id="cookie-message-close">Ok</a></span>
</div>

I am seeking guidance on how to achieve this functionality using jQuery. Any assistance would be greatly appreciated!

Answer №1

Utilizing an API can streamline the process of managing cookies, simplifying tasks.

Start by adding display: none; to the cookie-message div.

When it comes to determining whether or not the notice should be hidden, you can create a listener for the initial window load:

window.addEventListener('load', function(){...});

This allows you to detect when the window is fully loaded. If there is no cookie indicating that the notice has been read, display the div ($('#cookie-message').show()), and then set a cookie. If a cookie already exists for this purpose, take no action.

For handling the OK click, set up a click listener on the link to hide the notice div ($('#cookie-message').show()).

For assistance, I have created a basic example illustrating the steps mentioned.

Answer №2

Thank you for your helpful response, Henrique. Unfortunately, I encountered a problem with a "jQuery $.cookie is not a function" error.

After some research, I discovered that "jQuery Cookie" has been deprecated and the new version is called js-cookie. By incorporating this change and updating the old cookie functions to the new ones, I was able to resolve the issue successfully!

Here is my updated jQuery code utilizing "js-cookie":

window.addEventListener('load', function(){
    jQuery('#cookie-message-close').click(function(){
        jQuery('#cookie-message').hide();
    });

    if (!Cookies.get("cookie-message-bar"))
    {
        jQuery('#cookie-message').show();
        Cookies.set('cookie-message-bar', true, { expires: 60 });
    }
});

It's worth mentioning that I switched from using $ to jQuery due to Wordpress' noConflict() mode, as I am working within the Wordpress environment.

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 significance of AngularJS in crafting Single Page Applications?

My introduction to AngularJS was discovering its perfection for Single Page Applications (SPAs). I'm intrigued by what this means and eager to learn more about it. Can someone explain the significance of SPAs in relation to AngularJS? ...

Tips for successfully passing import as props arguments in React JS

I am using react-lotties and would like to add different animations to multiple divs by just changing the URL of the lotties As a beginner in React, please be kind :) This is my code snippet : My Lotties Component : import React, { Component } f ...

Navigate to a refreshed version of the page with varying parameters using React Navigation

Currently, I am utilizing React Navigation for navigating between different pages within my app. One of the pages is the Profile page which displays a user info card along with their posts. Within this Profile component, I have integrated the Post componen ...

`Can controllers be included in route or template definitions?`

When it comes to defining a route with a template, there are two main ways to set the controller for the view: In the route: $routeProvider .when('/phone/:phoneId', { controller: 'PhoneDetailController', templateUrl: &ap ...

The art of designing Mongoose and Router files

Let me share my directory structure with you: bin/ www models/ myMongooseModel.js public/ ... routes/ index.js anotherroute.js views/ ... app.js package.json In my app.js file, I have configured some settings using app.set and app.use comman ...

Ways to make two blocks of text appear side by side and adapt to different screen sizes

Check out our website imageI'm facing a challenge in making these two text elements appear next to each other rather than stacking on top of each other. Additionally, I need them to adapt responsively to changes in screen size. When 'Icontext&ap ...

CSS3 Rounded Corners

What is the most effective method to create this style of border using only CSS3? PS: The width should be 100%, matching the size of the screen. ...

Fill the second dropdown menu options based on the selection made in the first dropdown menu

I need assistance with dynamically populating my second drop-down menu based on the selection made in the first drop-down. Here are the steps I've taken so far: form.php - Utilizing javascript, I have set up a function to call getgeneral.php. The se ...

Determine if an object is empty in AngularJS

Is there a way to make a div element visible only after the user selects at least one checkbox? I attempted to achieve this using the following code within the div: <div class="col-md-1" ng-if="selectedElements.length > 0"> The variable selected ...

Transforming Vanilla JavaScript into a React application with modular components

I'm looking to transform this Sign In/Up Form into a React application by utilizing components. Since I'm new to React, I would appreciate some assistance with converting vanilla JavaScript into React components with sliding transitions. Can anyo ...

Split an array of simple data types in JavaScript into separate sections

Is there a way to divide an unordered array of primitive types into specific segments like this: var array = [102,103,104,201,203,204,303,301,302,405,406,408,101]; => newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]] The divi ...

Incorporating Javascript into a .Net MVC 3 Project

It seems like there should be a straightforward solution to my question, but I'm struggling with it. I have an animation.js file that includes dependency_1.js and dependency_2.js in an include folder. Within my animation.js file, I load these dependen ...

Minimize all the open child windows from the main Parent window

I would like to implement a functionality where, upon logging in, the user is directed to a Main Page that opens in a new window. This Main Page contains two buttons, each of which will open a specific report associated with it in a new window when clicked ...

Navigating on the horizontal axis within a container with overflow properties

I am trying to insert multiple children-divs into a parent-div. The parent div has a fixed width. The children are set to float left and will overflow the container. I need the ability to scroll along the x-axis. However, when I attempt to do this, the c ...

Issues have arisen with the functionality of noneditable contents in tinymce

I am currently using the tinyMCE editor and I need to make certain content readonly (nonEditable). According to the documentation, if I apply the class "mceNonEditable" to specific elements, it should meet this requirement. However, when I select that ele ...

Let us know when the information on a different tab is updated

I have multiple tabs and I want to indicate when a change occurs on another tab that the user hasn't clicked. For example, if the user hits the run button while on the Data pane, I would like the Errors tab to change to red to show that there was a ch ...

Troubleshooting the challenges with jQuery's next().addClass() and prev().addClass() functions

I am attempting to create a slider feature. I have four different contents that I've positioned consecutively, but made them invisible initially. I defined a class called active-client with the attribute display: flex. Using jQuery's addClass() m ...

Create HTML files that generate a log.txt document

It seems like every time I try to find a solution for writing files with PHP or JavaScript, I end up in a never-ending argument. Some say it's impossible, while others claim it's possible under certain conditions. Unfortunately, none of the code ...

What is the best way to make JavaScript display the strings in an array as bullet points on different lines?

We were assigned a task in our computer science class to analyze and extend a piece of code provided to us. Here is the given code snippet: <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body& ...

What is the best way to initiate the registration page through the @auth0/auth0-react library?

I've hit a roadblock in trying to automatically launch the sign-up (registration) page using @auth0/auth0-react. Previously, I would send mode which worked with auth0-js. So far, I have attempted the following without success: const { loginWithRedir ...