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

Tips for achieving a blurred background image effect when hovering, while keeping the text unaffected

Hey there, I've recently started my journey into web development and have encountered a roadblock. I'm trying to blur the background image of a div on hover without affecting the text inside. I have an id called c1 where I used a javascript func ...

The footer at the bottom of the page is currently malfunctioning

I was able to create an always on the bottom footer using code from Codepen. Here is the HTML: <div class="content"> <header> <p>blabla</p> </header> <main> <p>blaBlabla blub</p ...

What is the benefit of using an IIFE in this particular way when constructing a JavaScript library?

Many libraries I've seen use a similar style to define their structure. Upon further inspection, I've noticed that the first self-invoking function is often related to Require.js or AMD systems, with 'factory' as an argument. My curiosi ...

Optimizing jqGrid: Enhancing saveRow function to properly synchronize with editRow function

Exploring how to customize jqGrid's add function for my own needs. I have a navButton with specific requirements: When the user clicks the button, a new row in edit mode should appear on the grid. Once the user enters data and presses enter, the dat ...

Trouble arises when attempting to add an image to a spherical object

I've searched through various threads, Googled extensively, watched YouTube tutorials.... But I can't seem to figure out how to apply a texture to my Sphere. When I run this code, all I see is a white Sphere without any texture showing up. Can so ...

Custom value in Field for radio type in Redux form

Can anyone help me figure out how to input text into a radio field using Redux form? Here are the fields I am working with: <Field name={some.name1} value={'text1'} component={renderRadioElement} type="radio" /> <Field name= ...

Is there a way to associate a click event with an angular2 template interpolation?

Can a click event be bound to an interpolation? Whenever I try to run the code below, I encounter the following ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at col ...

Symfony2 - Utilizing an Entity repository to encode data into JSON for efficient AJAX calls

I'm currently working on implementing a dynamic text field with AJAX autocomplete functionality. In order to handle the AJAX call, I have created a method in the controller. public function cityAction(Request $request) { $repository = $this-> ...

Retrieve both positive and negative reviews using the Steam API

I'm trying to calculate the percentage of positive reviews, but I haven't been able to find the necessary data. I've been using this endpoint to retrieve game information: "", but it only provides the total number of reviews. I am aware of a ...

New features in Next.js 13 include an updated server component and enhanced fetch capabilities for re

Is it possible to toggle the URL from the getData function? I have my main page component with JSON todos. Can I replace 'todos' with 'users' in my client component? import styles from './page.module.css' import Button from "@ ...

Servlet unable to retrieve parameters from Form due to unexpected NULL values

Here is a basic form element for you to review: <form action="Test" method="POST" enctype="multipart/form-data"> <input type="text" name="first_name" title="First Name"></input> <input type="text" name="last_name" title="Las ...

PHP mistakenly outputs content that is not enclosed within tags

After discovering StackOverflow, I couldn't resist sharing my PHP code conundrum with the incredible community here! So, in a WordPress template, I have this chunk of PHP: echo '<div class="thumbnail">'; echo the_post_thumbnail(); ec ...

Are your Express routes failing to function properly?

I recently embarked on creating a new Express app by following the tutorial from Code Magazine. Below are my app and the defined route for /img. https://i.sstatic.net/G6PUG.png Upon trying to access http://localhost:3000/img or http://localhost:3000/img/ ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

Using Javascript to extract information from the div element

Within my HTML code, I have a total of 4 <div> tags and a corresponding <a> tag for each of these <div> tags. Inside each div tag, there are 2 span tags and an additional a tag. Upon clicking the a tag, I aim to extract the product name ...

Transforming complex mathematical equations into executable code using the node.js platform

Looking to implement a mathematical formula found at the following link: https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_bracelets into node.js for calculating the total number of distinct ring sequences that can be created with n length ...

The time.js library is providing inaccurate second values for the given date and time

Utilizing the moment.js library along with the Timezone and BusinessDays extensions in Vue.js, I am developing a datetime format for storing in a MySQL database. Here is the code snippet: import moment from 'moment-timezone' ...

Divs animated with jQuery keep on moving even after the animation has finished

My current project involves animating a single circle that scales, collides with two nearby circles, and then causes those circles to animate to specific positions. While everything works as expected, there is an issue where the two circles involved in the ...

Node.js and Socket.IO: Managing responses

In a unique scenario, the web page is initially served using HTTP. When the submit button is clicked, data is sent to the server and multiple web services are executed, which may take some time. The challenge is to quickly display the response page and the ...

Naming a JSON object twice

As a newcomer to node.js, I find myself struggling with understanding the process. Can someone please guide me on where I might be going wrong? This is how I create a new Product exports.postAddProduct = (req, res, next) => { const product = new Produ ...