Storing the closed state of a pop-up box in localStorage for future reference

I'm struggling to get localStorage working properly on my website ().

Here's what I need to achieve:

  • A newsletter subscription pop-up on every page - this part is functioning correctly
  • An option for users to click 'X' to close the pop-up - works fine as well
  • Remembering the closed state of the window so that users don't see the pop-up again on other pages - unfortunately, this functionality isn't working at all.

My approach was to use a localStorage variable and check if the window should be displayed or not based on that. However, it seems like my logic and syntax might be incorrect. Any guidance on the correct method would be highly appreciated.

This is the code snippet I've been experimenting with for the subscription pop-up:

<script>
function setSignup(val) {
localStorage.setItem("popState", val); 
}

function getSignup() {
$(window).on("load", function() {   
    if(localStorage.getItem("popState") == 'hide'){
        //$(".signup").hide();
        $(".signup").css("display", "none");
    }
    else if (localStorage.getItem("popState") != 'hide'){
        $(".signup").css("display", "block");
    }
});
}
</script>

<div class="signup">
<div class="signup-header">Sustainable Living</div>
<span class="closebtn" onclick="setSignup('hide');this.parentElement.style.display='none';">×</span>
<div class="signup-container">
<p>Receive articles on <em>sustainability</em> and <em>eco-friendly home decor</em> directly in your inbox. We value your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&amp;id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
    <div id="mc_embed_signup_scroll">
<div class="mc-field-group">
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="email">
</div>
    <div id="mce-responses" class="clear">
        <div class="response" id="mce-error-response" style="display:none"></div>
        <div class="response" id="mce-success-response" style="display:none"></div>
    </div>
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
</form>
</div>
</div>

Answer №1

It appears that your getSignup function is not being called correctly. Below is an alternative solution that does not use jQuery.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

</head>

<body>
  <script>
    function setSignup(val) {
      localStorage.setItem("popState", val);
    }

    function getSignup() {
      if (localStorage.getItem("popState") == 'hide') {
        //$(".signup").hide();
        document.querySelector('.signup').style.display = 'none';
      } else if (localStorage.getItem("popState") != 'hide') {
        document.querySelector('.signup').style.display = 'block';
      }
    }
    window.addEventListener("load", getSignup);
  </script>

  <div class="signup">
    <div class="signup-header">Sustainable Living</div>
    <span class="closebtn" onclick="setSignup('hide');this.parentElement.style.display='none';">×</span>
    <div class="signup-container">
      <p>Get new articles related to <em>sustainability</em> and <em>eco-friendly home decor</em> direct to your inbox. We respect your privacy.</p>
      <form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&amp;id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
        <div id="mc_embed_signup_scroll">
          <div class="mc-field-group">
            <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="email">
          </div>
          <div id="mce-responses" class="clear">
            <div class="response" id="mce-error-response" style="display:none"></div>
            <div class="response" id="mce-success-response" style="display:none"></div>
          </div>
          <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
          <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
        </div>
      </form>
    </div>
  </div>

</body>

</html>

Answer №2

Thank you for sharing your insights, everyone! I managed to resolve the issue by implementing the following solution (in case anyone else encounters a similar problem)...

HTML:

<div class="signup">
<div class="signup-header">Sustainable Living</div>
<div class="signup-container">
<p>Receive fresh articles on <em>sustainability</em> and <em>eco-friendly home decor</em> straight to your email. We value your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&amp;id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
    <div id="mc_embed_signup_scroll">
 <div class="mc-field-group">
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="email">
 </div>
    <div id="mce-responses" class="clear">
        <div class="response" id="mce-error-response" style="display:none"></div>
        <div class="response" id="mce-success-response" style="display:none"></div>
    </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
 </form>
 </div>
 </div>

CSS:

    .signup {
    bottom: 2%;
    display: none;
    margin-right: -15px !important;
    max-width: 280px;
    position: fixed;
    right: 2%;  
    z-index: 9999;  
}

.signup-header {
    background: #539c22;
    border-radius: 10px 10px 0 0;
    color: #ffffff;
    font-family: 'Carrois Gothic', sans-serif;
    font-size: 20px;
    padding: 25px 15px;
    text-transform: uppercase;
}

.signup-container {
    background-color: #6db240;
    border-radius: 0 0 10px 10px;
    color: #ffffff;
    padding: 15px;
}

.closebtn {
    color: #ffffff;
    cursor: pointer;
    font-size: 30px;
    position: absolute; 
    right: 15px;
    top: 5px;   
}

.closebtn:hover {
    color: #6db240;
}

.signup-container .button {
    background-color: #539c22; 
    border: 0 none;
    border-radius: 5px;
    color: #ffffff !important;
    cursor: pointer;
    font-size: 15px;
    height: 32px;
    line-height: 32px;
    margin: 0 15px 0 0 !important;
    text-align: center;
    transition: all 0.23s ease-in-out 0s;
    width: 100% !important;
}

.signup-container .button:hover {
    opacity: 0.7;
}

.signup-container .mc-field-group input {
    display: block;
    padding: 8px 0;
    text-indent: 2%;
    width: 100%;
}

.signup-container input {
    border: 1px solid #d0d0d0;
    border-radius: 5px;
    cursor: auto;
    font-family: 'Open sans', sans-serif; 
    font-size: 15px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px; 
}

JQuery:

$(document).ready(function() {

    $('.signup').css('display', 'block');

    $PopUp = $('.signup');

    var hide = JSON.parse(localStorage.getItem('hide'));

    if (hide) {
        $PopUp.hide();
    } else {
        // initialize value in case it hasn't been set already
        localStorage.setItem('hide', false);
    }

    $('.closebtn').click(function() {
        $('.signup' ).hide();
        // toggle the boolean by negating its value
        var hide = JSON.parse(localStorage.getItem('hide'));
        localStorage.setItem('hide', !hide);
    });
});

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

Disable setTimeout in Node.js triggered by an event

I am facing a dilemma with my code that constantly polls a service and I am looking for a way to efficiently cancel the interval using `clearTimeout` through events. The timeouts essentially act as intervals by calling setTimeout again within the function. ...

Creating a single-level menu with Bootstrap using nested angular ng-repeat

I am currently working on developing a single level menu using bootstrap and angularJS. The menu is successfully functioning with JavaScript and HTML when the <li> element is dynamically created. Now, I am attempting to integrate AngularJS into the ...

Sending data from Angular to the DOM

Is there a way to dynamically pass a property to an HTML tag using Angular? <div class="my-class" data-start="10"> I am trying to figure out how to pass the value of data-start dynamically. This is for an Angular 5 application. Any advice would be ...

What is the process for configuring environment variables in a React application?

I have set up my React app to run on http://localhost:3000, and now I am looking to configure environment variables for different environments such as development, production, staging, and local. These are the URLs for my React app in various environments ...

What is the correct way to utilize CSS for setting a responsive background image for an element?

When I set the background-image for an <a>, it always requires specifying the width and height in the stylesheet file. This causes the URL image to not be responsive. I've tried solutions such as using background-size: cover; and background-colo ...

I am seeking to retrieve data from MongoDB by utilizing the limit feature, while also sending a specific query

I'm currently facing some confusion with the limit functionality in MongoDB. I want my code to specifically retrieve data for just two hotels by sending a query request from the backend. export const getHotels = async (req, res, next) => { try ...

What is the best way to bring in a service as a singleton class using System.js?

I have a unique Singleton-Class FooService that is loaded through a special import-map. My goal is to efficiently await its loading and then utilize it in different asynchronous functions as shown below: declare global { interface Window { System: Sy ...

Is there a way for me to adjust the font size across the entire page?

Most CSS classes come with a fixed font-size value already set. For instance: font-size: 16px font-size: 14px etc. Is there a way to increase the font size of the entire page by 110%? For example, font-size: 16px -> 17.6 font-size: 14px -> 15.4 ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

Nextjs unexpectedly displays blank page upon fetching data from Firebase Firestore without any error messages

I am currently facing an issue when trying to retrieve page details from Firebase Firestore using getStaticPaths and getStaticProps in my Next.js project. Despite following the code structure correctly, I am encountering a scenario where the page appears e ...

"Encountering an issue when linking the file with phpMyAdmin

I've been struggling with this issue for hours now. I'm currently working on a registration form for my website and while coding in PHP, I connected it to MySQL and the Database using this line of code (which happens to be the 6th line): $mysq ...

Generate a dynamic animation by combining two images using jQuery

My attempt to animate two images is not working. I received some help on Stack Overflow but still facing issues with my CSS and HTML code. This is the code I am using: $(document).ready(function() { $(".animar").click(function() { $("#img4" ...

When using jQuery to focus on an input element, the cursor fails to show up

Looking to enhance user experience by focusing on an input element upon clicking a specific div. The HTML structure being used is as follows: <div class="placeholder_input"> <input type="text" id="username" maxlength="100" /> <div ...

Finding the file in a separate directory within the src path

In my projects directory, I have a folder named projects which contains both a game folder and an engine folder. Inside the engine folder, there is an engine.js file. My issue is that I want to access this engine.js file from my game.html file located in a ...

The unexpected blank space appearing beneath my website as a result of images and videos placed on the

There seems to be some random white space on my website between the main body elements and the footer. Interestingly, removing the cat image and videoplayer eliminates this white space. However, I don't want to remove them completely, so I'm tryi ...

The request cannot be completed using GET. The connection has not been established, and the offline queue is not activated

Encountering this unexpected error in the live environment, despite implementing a retry strategy of 500ms and wrapping the setAsync and getAsync functions with a setTimeout of 1s. It's puzzling why this issue persists. Error Message: AbortError at ...

Changing the color of a marker on hover in Mapbox using leaflet.js

I have encountered an issue where setting the geojson triggers the mouseover event, causing an infinite loop and breaking functionality. I managed to fix it by changing it to click, but now I need to figure out how to make it work with hover. My goal is t ...

Delay in form submission

I am attempting to auto-submit a form with its value after 10 seconds. I am having trouble incorporating a setTimeout function with the submit action. setTimeout(function() { $('#FrmID').submit(); }, 10000); $(document).ready(function() { ...

What is the best method for retrieving the current value of an RxJS Subject or Observable?

I am dealing with an Angular 2 service: import {Storage} from './storage'; import {Injectable} from 'angular2/core'; import {Subject} from 'rxjs/Subject'; @Injectable() export class SessionStorage extends Storage { priv ...

Updating the KML data on Google Maps V3 for a fresh look

I recently updated a map from V2 to V3 and I am working on incorporating code to automatically refresh the KML data every 30 seconds. The goal is to update the map with the latest data and display a countdown until the next refresh. Here is an example of ...