Clear out all current cookies

I utilized the following JavaScript code to generate a pop-up window on the website that would only appear once. However, my client now wants to launch a new promotion and I am attempting to remove existing cookies so that the pop-up window displays again for returning visitors (just once as before). Here is the current script:

<!--
function setCookie(name, value, expires, path, domain, secure) {
 var curCookie = name + "=" + escape(value) +
   ((expires) ? "; expires=" + expires.toGMTString() : "") +
   ((path) ? "; path=" + path : "") +
   ((domain) ? "; domain=" + domain : "") +
   ((secure) ? "; secure" : "");
 document.cookie = curCookie;
}

function setCookie(name, value, expires, path, domain, secure) {
 var curCookie = name + "=" + escape(value) +
   ((path) ? "; path=" + path : "") +
   ((domain) ? "; domain=" + domain : "") +
   ((secure) ? "; secure" : "") +
    ((expires) ? "; expires=" + expires.toGMTString() : "") ;
 document.cookie = curCookie;
}


function getCookie(name) {
 var dc = document.cookie;
 var prefix = name + "=";
 var begin = dc.indexOf("; " + prefix);
 if (begin == -1) {
  begin = dc.indexOf(prefix);
  if (begin != 0) return null;
 } else
  begin += 2;
 var end = document.cookie.indexOf(";", begin);
 if (end == -1)
  end = dc.length;
 return unescape(dc.substring(begin + prefix.length, end));
}
function pop()
{
 $(document).ready(function() {
    $('#myModal').reveal();
});
}
var seen = getCookie("seen");
if (!seen) {
var now = new Date();
now.setTime(now.getTime() + 360000 * 1000);
setCookie("seen", 1, now);
pop();
}
//-->

I attempted the following steps to reset the cookies

<!--
function setCookie(name, value, expires, path, domain, secure) {
 var curCookie = name + "=" + escape(value) +
   ((expires) ? "; expires=" + expires.toGMTString() : "") +
   ((path) ? "; path=" + path : "") +
   ((domain) ? "; domain=" + domain : "") +
   ((secure) ? "; secure" : "");
 document.cookie = curCookie;
}

function setCookie(name, value, expires, path, domain, secure) {
 var curCookie = name + "=" + escape(value) +
   ((path) ? "; path=" + path : "") +
   ((domain) ? "; domain=" + domain : "") +
   ((secure) ? "; secure" : "") +
   **";expires=Thu, 01 Jan 1970 00:00:01 GMT";**
 document.cookie = curCookie;
}


function getCookie(name) {
 var dc = document.cookie;
 var prefix = name + "=";
 var begin = dc.indexOf("; " + prefix);
 if (begin == -1) {
  begin = dc.indexOf(prefix);
  if (begin != 0) return null;
 } else
  begin += 2;
 var end = document.cookie.indexOf(";", begin);
 if (end == -1)
  end = dc.length;
 return unescape(dc.substring(begin + prefix.length, end));
}
function pop()
{
 $(document).ready(function() {
    $('#myModal').reveal();
});
}
var seen = getCookie("seen");
if (!seen) {
var now = new Date();
now.setTime(now.getTime() + 1 * 1000);
setCookie("seen", 1, now);
pop();
}
//-->

The changes are not taking effect. As a newcomer to JavaScript, any assistance you can provide would be greatly appreciated!

Answer №1

It appears that you have quite a tidy piece of code here, so if I've grasped it correctly, this snippet should get the job done:

// When the document is ready
$(function(){

    // Check for the old cookie and delete it
    if( Cookies.Check('seen') ) Cookies.Set('seen', '', -1); // Delete the cookie if it exists

    // Now work with a new one under a different name
    if( !Cookies.Check('newmodal') ){ // If the cookie doesn't exist, show the modal and set the cookie
        $('#myModal').reveal();
        Cookies.Set('newmodal', 'true', 365); // Set for number of days; use minutes if needed (see method below)
    } // No `else` statement since nothing happens if the cookie exists
});



/**
 * Object containing methods to handle cookies
 * @type Object
 */
var Cookies = {

    /**
     * Checks if a specific cookie exists
     * @param {String} name
     * @return Boolean
     */
    Check: function (name) {
        return !!this.Get(name);
    },

    /**
     * Retrieves value of a specified cookie or returns false
     * @param {String} name
     * @return String|Boolean
     */
    Get: function (name) {
        var n, ca, c;
        n = name + "=";
        ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            c = ca[i].trim();
            if (c.indexOf(name) === 0) return c.substring(name.length + 1, c.length);
        }
        return false;
    },

    /**
     * Sets a new cookie
     * @param {String} name
     * @param {String} value
     * @param {Number} [expiration]
     * @param {Object} [options]
     * @return Boolean|void
     */
    Set: function (name, value, expiration, options) {
        var d = new Date(), expires;
        var defaults = { expire_in: 'days', path: '/' };
        if (typeof options !== "undefined") $.extend(true, defaults, options);
        if (expiration !== undefined && expiration !== null) {
            if (defaults.expire_in == 'days') d.setDate(d.getDate() + expiration);
            else if (defaults.expire_in == 'minutes') d.setDate(d.getTime() + expiration * 1000);
            else {
                throw new JUtils.EX('expire_in configuration is not valid');
            }
            expires = "expires=" + d.toGMTString();
        }
        else expires = expires = "";
        document.cookie = name + "=" + value + "; " + expires + '; path=' + defaults.path;
        return true;
    }

};

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

Showing button based on a particular value

I am trying to dynamically display a button based on the value of the sendSMS property for the logged-in user. I have added this property in the viewer model, which is connected to the user's base model. However, I am encountering difficulties with us ...

Dynamic Creation of a jQuery Selector

Dear, I'm facing an issue while trying to load data dynamically into a table using JSON format. The data is coming from a PHP file. However, despite my attempts, the table remains empty and no data is being displayed. function fetchTableData() { ...

JavaScript: The variable `scopes` is declared

I'm completely new to JavaScript. Can anyone help me understand why this code isn't working, and what changes I need to make to fix it? function getResults(keywords) { foo.foo = function() { var bar = foo.getSomeText; // ...

``Look at that cool feature - a stationary header and footer that stay in place

I'm seeking advice on how to design a website with a fixed header and footer that remain consistent across all pages, with only the content area altering. I've come across a site as an example - , but couldn't figure out how it was done even ...

Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge. const example = { myFunction(){ console.log(this); }, myFunction2(){ function myFunction3(){ console.log(this) } return ...

Tips for assigning a class name to a variable element within a react component?

I am interested in dynamically adding classes to an element. While I am familiar with methods using html-dom and passing a JavaScript expression to className, I am seeking a different approach. Is there a way to add classes similar to pushing them to an ar ...

Evaluating the functionality of a React JS dropdown using Selenium automation and Java

Could you please advise me on how to select a value from a dynamically populated dropdown using React JS? An example would be greatly appreciated. Below is the HTML code snippet for the page... The division that contains the label "Year" functions as ...

Learn the process of adding asynchronous middleware modules to your express.js application

I'm currently developing an express application that utilizes the node_acl module along with a MongoDB database. I have created a custom module that sets up and configures node_acl asynchronously. This middleware needs to be called as the second piece ...

json data hidden from sight in jQuery

Snippet of HTML Code: <select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);"> <option value="">--Select--</option> <option value="Value11">Value1</option> <option value="Value2">Value2</op ...

Is there a problem with the alignment of

<s:form id="inputThresholdForm" name="inputThresholdForm" theme="simple"> <table border="0" class="display-table" cellspacing="2" cellpadding="2" height="100%" width="100%"> <tr> <td colspan= ...

Is it possible to close the navigation menu by clicking on a link or outside of the navigation area?

Hey everyone, I've recently dived into the world of web design and encountered my first hurdle. I need your expertise to help me solve this problem. How can I modify my JavaScript to close the NAV element by clicking on one of the links or outside t ...

How can I troubleshoot the unresponsive remove div function on my website?

My code is running fine on CodePen (link provided below), but for some reason, it's not working properly in the web browser. I am executing the code from localhost and the button isn't responding as expected. CODE Here is my Visual Studio code ...

Unable to connect to node.js webserver using the godaddy shared hosting URL

Upon entering www.example.com:3000 into my browser, I am encountering the following error message (where 'example' represents my domain name) This site can't be reached - www.example.com took too long to respond. I have taken the following ...

What is the best way to determine whether a YouTube video permits embedded playback?

When working with user-generated content, it's important to note that YouTube channels may restrict their videos from being played in an embedded player. In order to provide a better user experience, I need to detect the specific reason why a video ca ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

Having trouble with Javascript in getting one-page scroll navigation to work?

Hey there, I am working on creating a one-page scroll navigation with some basic javascript to add a smooth animation effect that takes 1 second as it scrolls to the desired section. However, I seem to be experiencing an issue where it's not functioni ...

What is the process of comparing one regular expression against another in JavaScript?

I'm looking to check for matches between two regular expressions. To achieve this, I use the .test method on each one. If either of them returns true, I consider them a match. const regexify = (str) => new RegExp( '^' + str ...

As soon as I closed the modal, I noticed that the checked inputs reverted back to

I am using checkboxes within a modal to narrow down my search results. However, I have encountered an issue where when I check multiple checkboxes and then close the modal, the checked inputs become unchecked. Every time I open the modal, I want the check ...

Exploring the possibilities of reading and writing data in localStorage?

Just starting out with Phonegap, jQuery Mobile, and HTML5 - so please bear with me as I navigate through this learning process! I'm having an issue and could use some help. When trying to use a variable from localStorage, the screen remains blank whe ...

Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...