Tips for Maintaining the Execution of a JavaScript Function Within a Class until the Browser Window is Closed (Web Development)

The title might be a little confusing, so let me clarify here:

I have implemented a popup that appears in the bottom right corner of a specific page on my website. The popup is working as intended (it shows up when the page is initially opened and can be closed by clicking the 'x' icon). However, when I navigate away from the page to other sections of the site and then return, the popup resets and reappears even if it was previously closed. Is there a way to keep the popup hidden until the tab is closed or the visitor leaves the website?

function closePopup() {
  document.getElementById("pop-up").classList.toggle("hide");
}
#pop-up {
  position: absolute;
  bottom: 7%;
  right: 0;
  height: 50%;
  width: 30%;
  background: #F0F0F0;
  border-top: solid 5px rgb(25, 28, 31);
  border-bottom: solid 5px rgb(25, 28, 31);
  border-left: solid 5px rgb(25, 28, 31);
}

#pop-up p {
  text-align: center;
  margin: 5%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.hide {
  opacity: 0;
  animation-name: hide;
  animation-iteration-count: 1;
  animation-duration: 0.75s;
}

@keyframes hide {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
<div id="pop-up">
  <i onclick="closePopup()" class="fas fa-times fa-2x" style="padding: 4%; float:right;"></i>
  <p>Feature your logo here! If you are interested in becoming a sponsor, please contact us at <a href="mailto:sponsor@example.com">sponsor@example.com</a>.</p>
</div>

Answer №1

It seems like the solution you're looking for is right here,

Initially, the popup remains hidden. Upon triggering the window load event, if there is no 'hidepopup' key saved in sessionStorage, the popUp will be displayed. When it's closed, the fcnx1 function will create the 'hidepopup' key in sessionStorage, which will persist until the browser is closed.

I've also updated the animation in your CSS to an animated transition, which should suffice for this scenario.

You can find more information about window.sessionStorage here

Please note that trying the code snippet here won't work as Stack Overflow's fiddle is sandboxed and doesn't allow access to sessionStorage.

For a working example, you can check out the codepen: https://codepen.io/Teobis/pen/ZRdQwL?editors=1111

function fcnx1() {
      sessionStorage.setItem('hidepopup', true);
        document.getElementById("pop-up").classList.toggle("hide");
        }

window.addEventListener("load", function(event) {
  console.log(sessionStorage.getItem('hidepopup'))
  if(sessionStorage.getItem('hidepopup') == null){
    document.getElementById("pop-up").classList.toggle("hide")
  };  
})
#pop-up {
  position: absolute;
  bottom: 7%; 
  right: 0;
  height: 50%;
  width: 30%;
  background: #F0F0F0;
  border-top: solid 5px rgb(25,28,31);
  border-bottom: solid 5px rgb(25,28,31);
  border-left: solid 5px rgb(25,28,31);
  transition:all 385ms linear;
}

#pop-up p {
  text-align: center;
  margin:5%;
  position: absolute;
  top:50%;
  transform: translateY(-50%);
}

.hide {
  opacity: 0;
}
<div id="pop-up" class="hide">
    <i onclick="fcnx1()" class="fas fa-times fa-2x" style="padding: 4%;             
    float:right;"></i>
 
    <p>Have your logo here! If you are interested in becoming a sponsor, 
    feel free to email us at <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe8d8e91908d918c8b3a1a6a2b5a6b1a2b6b7edaeb9a4">[email protected]</a>"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3b0b3acadb0acb883a1a6a2b5a6b1a2b6b7efa4b9a4b1">[email protected]</a></a>.</p>
</div>

I trust this explanation is helpful.

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

verified that all form checkboxes were selected in angularJS

Hey there, I have a form in AngularJS with multiple checkboxes. When the first checkbox (Check All) is clicked, I want all the checkboxes to be checked. How can I achieve this using Angular for each field loop? Below is a snippet of my code: vm.asas = f ...

Using getServerSideProps in Next.js is preventing the global css from loading

In my Next.js application, I have defined global styles in the file /styles/globals.css and imported them in _app.tsx. // import default style import "../styles/globals.css"; function MyApp({ Component, pageProps }) { return <Component {...pageProps ...

File or directory does not exist: ENOENT error occurred while trying to scan 'pages'

Having trouble adding a sitemap to my nextjs app - when I go to http://localhost:3000/sitemap.xml, I get this error: Error: ENOENT: no such file or directory, scandir 'pages' https://i.sstatic.net/cxuvB.png The code in pages/sitemap.xml.js is a ...

Angular method $http.get is failing to function as intended

This is the HTML and JavaScript code I have written. <!DOCTYPE html> <html ng-app> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name ...

Testing multiple regex patterns using jQuery

I am attempting to run multiple regex tests on an input field. Here is the script: $("#search-registration").keyup(function () { var input_data = $('#search-registration').val(); var regexTest = function() { this.withPrefix = /^ ...

Monitoring user logins based on user identification

How can I effectively monitor the activity of users who have logged into a web application that is managed by an external company? Despite my extensive research efforts, as a non-technical individual, I am struggling to understand how to utilize Google Ana ...

Creating a Music Bingo game to ring in the New Year

Looking to create a Music Bingo game for New Year's Eve with randomized songs that can be selected, but experiencing an issue where nothing happens when you have 4 in a row. Attempted adding a submit button, but it doesn't trigger any action. Ide ...

Checking the conditions and return statements within Jest testing framework

I recently started diving into Jest and am looking for alternative methods to test this function regarding the If case and return statement using Jest. Here is the function I need help testing: const extractInfo = (description: string) => { cons ...

Formik integration issue with MUI DatePicker causing error message: "date.isBefore is not a function"

I'm currently creating a form in React using Formik and MUI components. However, I encountered an error that says: date.isBefore is not a function TypeError: date.isBefore is not a function at DayjsUtils.isBeforeDay (http://localhost:3000/static/j ...

Unusual css glitch observed when hovering over a span/link

Currently, I'm struggling with a CSS code issue. My goal is to have the div #hidden show when someone hovers over the link in #trigger. <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> ...

Crop and resize a portion of an image using CSS

Is there a way to display just part of an image on a webpage and scale that specific area either larger or smaller using CSS? A common method is by using the following code: $("#myDiv").css({ width: 100, height: 100, background: "url('myurl.jpg ...

Creating a Distinct Interior Array Separate from the Exterior

I'm currently working on a project that involves creating a 2D array. I want the interior elements of this array to be black while the exterior elements should be white. However, my 2D array doesn't seem to be forming correctly - it looks more li ...

Creating an SVG element that adjusts to the size of its parent container: tips and tricks

I'm attempting to achieve the following: Displaying an SVG square (with a 1:1 aspect ratio) inside a div element. When the width of the div is greater than its height, the square should adjust to fit within the container based on the height (red box ...

What could be causing this Form to redirect to the incorrect file path?

I recently updated the login menu for my Admin panel. Initially, the login page was named login.php, but I decided to change it to index.php. Even though I made sure to update the action from login.php to index.php, when I click on the login button it st ...

Incorporate a caret into an element using CSS styling

issue I encountered an issue where <textarea> and Javascript had some quirks when trying to transfer the value into a <pre> tag. My aim was to implement a blinking caret in the <pre> as if I were pressing F7. The reason behind not using ...

Tips for maintaining the position of a camera in three.js while also keeping its rotation fixed on the origin

In three.js, I'm looking to dynamically adjust my camera's position while ensuring that its rotation automatically aligns with the world origin. For instance, if the camera is initially set at: camera.position.set(25,25,25) I aim to have the ...

Need help with TypeScript syntax for concatenating strings?

Can you explain the functionality of this TypeScript syntax? export interface Config { readonly name: string readonly buildPath: (data?: Data) => string readonly group: string } export interface Data { id: number account: string group: 'a&a ...

Facing issues with Heroku and Express/Nodejs crashing?

I have been working on a React/Express application that I am attempting to deploy on Heroku. While trying to do so, I encountered the following errors in my logs: 2020-01-13T03:39:48.733455+00:00 heroku[router]: at=error code=H10 desc="App crashed" method ...

Rows within distance

There seems to be too much space between the grid rows. I tried adding more photos or adjusting the height of the .image class to 100%, but then the image gets stretched out. The gap between items with classes .description and #gallery is too wide. When ...

Tips for disabling scrolling on a <div> using another <div> as a lock

I am facing an issue with a page where a div is appended to the body of an HTML. The problem is that there are two scrolls appearing - one on the new overlaying div and another behind it. Here is an approximate structure of the page, how can I ensure that ...