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

having trouble loading marker in react leaflet within next.js

I am facing difficulty in implementing react leaflet Marker in my next.js project. Below is the code snippet where I have included my map component: const MapSearch = dynamic(import('../../components/Map'), { ssr: false, loading: () => ( ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...

How can I submit a form using Ajax and save the response data?

I'm currently using a form to send SMS data to the sms.php page for processing. However, I want to submit the form data without redirecting to the sms.php page. Instead, I would like the data to be processed on the same page using Ajax. Although I hav ...

Leverage JavaScript to run a snippet of PHP code directly (without utilizing a separate PHP file)

I am looking for a way to integrate PHP into my web page using JavaScript and AJAX. I want the PHP file to be included and executed as if it is part of the native page, allowing me to utilize features like GET requests. <div id="firstAjaxDiv">Defaul ...

How come props do not get updated along with state changes?

I've encountered an issue where the state of a component being passed into another component as a prop is not updating correspondingly. Various attempts have been made to resolve this, including placing it in the return function and updating the "low ...

Different Ways Split Button Format Can Vary Based on Web Browser

I am encountering a formatting issue with a jQuery splitbutton on my webpage. In order to adhere to my company's design standards, I am essentially converting a link into a button. The functionality works perfectly fine; however, depending on the brow ...

Produce HTML content onto Google Drive Documents using JavaScript

Currently, I am working on a project that requires me to render the HTML form output in a new Google Docs document (a Word file, not a spreadsheet). Despite my efforts to find information online, all I can come across is related to spreadsheets. The main ...

Enhancing the efficiency of JavaScript code

Imagine you have a web application processing 1,000,000 user logins per hour. and the code below is executed during each user login: if (DevMode) { // make an Ajax call } else if (RealMode) { // make another Ajax call } else { // Do something ...

I'm attempting to make this script function correctly when an image is loaded

Can anyone help me figure out how to make this script function on image load instead of onclick? I came across the script on stackoverflow, but it was originally set up for onclick. I want it to work for onload or .load HTML====== <div id="contai ...

Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code? <div class="square red"></div> <div class="square blue"> ...

What could be causing AngularJS to fail to send a POST request to my Express server?

I am currently running a Node Express server on localhost that serves a page with AngularJS code. Upon pressing a button on the page, an AngularJS controller is triggered to post a JSON back to the server. However, I am facing an issue where the post requ ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

Customize Date Display in Material-UI DataGrid

How do I change the date format in MUI DataGrid from mongo's format to moment.js? In addition, I would like to add a new field with an edit icon that, when clicked, will redirect to the edit page. Here is what my code looks like: const columns = [ ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

Leverage environment variables within your index.html file

Currently, I am using Angular and I am encountering an issue while attempting to utilize an environment variable in my index.html for Google Analytics. I have attempted the following approach: <script> import {environment} from "./environments/e ...

What is the best way to incorporate JavaScript code as React syntax?

For my project, I am using the OpenLayers API Map. I'm unsure of the correct way to incorporate JavaScript code in React or vice versa. Here is an answer on how to use markers in the map, but I am struggling to implement it in my current code since I ...

When using Vuepress behind a Remote App Server, pages containing iframes may return a 404 error

Creating a static website using Vuepress was a breeze, especially since I included a dedicated section for embedded Tableau dashboards. The website functioned perfectly when accessed online without any issues, displaying the Tableau dashboards flawlessly. ...

Fixing the height of the body padding with JS or JQuery for a

I have a rather straightforward question that pertains to an issue I am facing while building a website using BS4. Specifically, my problem revolves around a fixed-top navbar with the class "fixed-top". The challenge stems from not knowing the actual heig ...

Having trouble with Isotope masonry functionality

While experimenting with Isotope from , I tested the reLayout method using the provided example found at . I copied the css and js to my page () but encountered an issue where clicking on the first element caused all other elements to move to the first col ...

Implementing the sorting feature in Angular JS to properly align sub sections with their correct parent sections

I'm facing an issue with the functionality of my sample code. Users can add sections and subsections within those sections, which are sortable using ui-sortable. However, after sorting the items, if I try to add a new sub-section to Section 2, it wron ...