Display a hidden div only when a cookie is set during the initial visit

I'm currently facing an issue while trying to set multiple cookies based on the existence of a div using JavaScript. On the first visit, I want to display the div to the user if it exists, then set a cookie (named redCookie) that expires in 3 days. Upon setting the cookie, the div should not be displayed on page refresh. However, after 3 days, I want the div to be shown again using redDiv.show().

Currently, the div appears on every page refresh. The cookie is indeed being set, but it keeps showing up every time. There seems to be a problem with my if statement, but I can't quite figure it out.

if ((redCookie === true) && (redDiv.length > 0))

Here is a link to the JSFiddle for reference: https://jsfiddle.net/9uh96bh7/

Below are my defined functions:

$( document ).ready(function() {
    colourCookies();
});
function colourCookies () {
    var redCookie = getCookie("red-cookie-name");
    var redDiv = $('.red');
    var yellowCookie = getCookie("yellow-cookie-name");
    var yellowDiv = $('.yellow');

    if ((redCookie === true) && (redDiv.length > 0)) {
        redDiv.show();
        setCookie("red-cookie-name", redCookie, 3);
        console.log('Red cookie is set');
    } else {
        redDiv.hide();
    }
    if ((yellowCookie === true) && (yellowDiv.length > 0)) {
        yellowDiv.show();
        setCookie("yellow-cookie-name", yellowCookie, 3);
        console.log('Yellow cookie is set');
    } else {
        yellowDiv.hide();
    }
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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 "";
}

Answer №1

Let's start with the code.

It's crucial to have

if ((redCookie == true) && (redDiv.length > 0))
instead of
if ((redCookie = true) && (redDiv.length > 0))
.

Remember, = is for assignment, while == is for equality.

Next, let's discuss the logic.

If cookie is set -> hide div
If cookie is not set -> show div, set cookie
(Correct me if I have misunderstood.)

Therefore, the correct if statement should be:

if (redCookie == true){
    //hide div
} else {
    //show div
    //set cookie
}

Lastly, there was an error in setting cookies. You should set your cookie like

setCookie("yellow-cookie-name", true, 3);

If you use

setCookie("yellow-cookie-name", yellowCookie, 3);
and yellowCookie happens to be null, it will cause your if statement to fail.

Answer №2

It seems that the issue lies in setting cookies, especially with certain browsers like Chrome not setting cookies when running locally. Try hosting it on a server or running it through Visual Studio to see if that resolves the problem. If hosting it on IIS is an option, give it a try. Alternatively, you can use localStorage as shown below...

$( document ).ready(function() {
colourCookies();
});
function colourCookies () { 

removeIfThreeDaysElapsed('red-ls');
removeIfThreeDaysElapsed('yellow-ls');

if (!localStorage.getItem('red-ls')) {
    $(".red").show();
    localStorage.setItem("red-ls", new Date().toGMTString());
} else {
    $(".red").hide();
}
if (!localStorage.getItem('yellow-ls')) {
    $(".yellow").show();
   localStorage.setItem("yellow-ls", new Date().toGMTString());
} else {
     $(".yellow").hide();
}
}

function removeIfThreeDaysElapsed(lsname){
  var d1 = localStorage.getItem(lsname);
  if(d1){
   if(new Date() > new Date(new Date().getTime()+(3*24*60*60*1000))){
   localStorage.removeItem(lsname);
   }
  }
}

Ensure to modify the code to handle different scenarios accordingly.

If you can see the cookie in the browser, consider adding a validation check like the one below...

if (redCookie) {
    redDiv.hide();
} else {   
    redDiv.show();
    setCookie("red-cookie-name", true, 3);
}

Keep in mind that when retrieving the value from a cookie, its datatype may be converted to a string, so it's advisable to either use the suggested method above or check for redCookie === "true".

I hope this information proves useful in resolving the issue.

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

Is there a way to add a fade-in and slide-in effect to this dropdown JavaScript, as well as a fade-out and

Although I lack the necessary knowledge of Javascript, I am aware that my request may be a bit much. The code I currently have is directly from the w3school dropdown-list demo. Would it be possible for you to help me implement a fade in and slide in effect ...

To enhance user experience, consider incorporating a 'Next Page' feature after the completion of every four paragraphs,

Here is a code snippet that can be used to print 'n' number of paragraphs: <% while(rs.next()){ String para=rs.getString("poems"); %> <p> <%=para%> </p> <!-- n number of p tags are printe ...

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...

implementing automatic ajax requests when user scrolls

This is a piece of JavaScript code: $(window).scroll(function() { $.ajax({ type: "GET", url: "not_data.php", data: dataString, success: function my_func () { //show new name ...

What could be causing justify-content: flex-start; to not function as expected?

Can someone help me with my flexbox navbar? I set the justify-content property to flex-start, but the content inside the container is not aligning correctly. You can see the output and code here: output html, body { backgr ...

Seamless social login integration for registering with Stormpath

Transitioning from C# and PHP to Node.js has presented some challenges, especially when working with the Stormpath API. I am currently trying to integrate social login on the registration page, but the pre-built option only allows it on the Login page. Al ...

Choosing the Best Websocket Libraries for Spring Boot and Angular Communication

In my exploration, I've discovered two methods for linking a Spring Boot backend with an Angular frontend: Using the regular spring-websocket broker with Stomp along with Angular StompJS and SockJS. Utilizing netty-socketio, a Java port of socketIO, ...

Modify an array by incorporating values from another array that have a matching property

I have two arrays that look like this let array1 = [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 3, 'name': ' ...

Executing filepicker.io Javascript API calls may lead to unsafe errors in Javascript

I am currently using AngularJS and encountering an issue when trying to call filePicker.pickAndStore from my Upload controller. Every attempt to use a filepicker.io API function triggers an "Unsafe Javascript attempt" error: The frame requesting access ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Guide on implementing factory updates to the display

I am attempting to update a reference within my factory in an asynchronous fashion, but I am not seeing the changes reflected in my view. View <div ng-repeat="Message in Current.Messages">{{Message.text}}</div> Controller angular.module(&ap ...

Issue with inconsistent functionality of Socket.io

I've encountered an issue while working with multiple modules - specifically, socket.io is not functioning consistently... We have successfully implemented several 'routes' in Socket.io that work flawlessly every time! However, we are now ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

How can I prevent the jQuery animation from moving elements by adjusting the border?

I've been working on a small jQuery script that animates the border of images when hovered over. However, I've run into an issue with unwanted repositioning of adjacent images due to the border width increase. $(document).ready(function(e) { ...

Enhance your website with dynamic effects by incorporating CSS3 columns and responsive layouts. Utilize CSS3 or jQuery/JavaScript to

I have decided to create a masonry style layout using CSS3 for the columns, which has made building the layout easier and more precise. This is especially useful as I am working on a responsive design. Currently, I am implementing CSS3 media queries to ad ...

Two objects precisely located in the same spot yet not visible simultaneously

There are two elements here. One is a transparent button, and the other is an image positioned behind it. The background property didn't work for me, so I attempted different variations without success: .top-container > button { background-ima ...

When the App is opened, Firestore triggers a function to run, and then again after any changes

I am looking to activate this function when the App is launched, and then whenever there is an update in my firestore data. export const getDuettsPlayer1 = (setDuetts) => { duettsRef.where("player1", "==", firebase.auth().currentUs ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

What steps can be taken to enable JSONIX to handle additional XML elements during the deserialization process?

JSONIX 2.0.12 is truly impressive. I am working with a substantial XML file and I am only looking to convert certain elements into JSON format. Whenever I omit some elements from my mapping file, JSONIX throws an unexpected element error during deseriali ...

Simple linking inside a Div container

I'm working on a div that has the following markup: <div class="col-sm-12"> <p class="bg-info">Basic Information</p> </div> Here's how it currently looks: I want to add an 'Add /Edit' link to t ...