What is the best way to show a pop-up message to a visitor on my site for the first time

I am seeking a way to showcase a popup the first time a user lands on my website. At present, the popup appears only upon page refresh. Check out the demo below:

var popupdisplayed = false;

jQuery(function() {
  jQuery('[data-popup-close]').on('click', function(e) {
    var targeted_popup_class = jQuery(this).attr('data-popup-close');
    jQuery('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);
    e.preventDefault();
  });
});

jQuery(document).ready(function() {
  jQuery('.popup').show(0);
  var halfbrowserHeight = jQuery(window).height() / 2;
  jQuery(window).scroll(function() {
    var distance = jQuery(window).scrollTop();
    if (distance >= halfbrowserHeight && !popupdisplayed) {
      jQuery('.popup').show(0);
      popupdisplayed = true;
    }
  });
});
a {
  text-decoration: none;
}

.popup-inner p a {
  text-decoration: none;
  color: #f8f341;
  font-family: 'Yeon Sung', cursive;
}

.popup {
  width: 100%;
  height: 100%;
  display: none;
  position: fixed;
  top: 0px;
  left: 0px;
  background: rgba(0, 0, 0, 0.75);
  font-family: 'Raleway', sans-serif;
}


/* Styling for Inner Portion of Popup */

.popup-inner {
  line-height: initial;
  max-width: 700px;
  width: 90%;
  padding: 0px;
  position: absolute;
  top: 50%;
  z-index: 99;
  text-align: left;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 1);
  border-radius: 3px;
  background: #40434c;
  background-size: cover;
  color: #FFF;
}

/* Close Button Styles */

.popup-close {
  width: 30px;
  height: 30px;
  padding: 4px 2px 0px;
  display: inline-block;
  position: absolute;
  top: 0px;
  right: 0px;
  transition: ease 0.25s all;
  -webkit-transform: translate(50%, -50%);
  transform: translate(50%, -50%);
  border-radius: 1000px;
  background: #FFF;
  font-family: Arial, Sans-Serif;
  font-size: 20px;
  text-align: center;
  line-height: 100%;
  color: #000 !important;
}

.mybtn {
  width: calc(50% - 60px);
  float: left;
  display: inline-block;
  background: #FFF;
  color: #000;
  text-align: center;
  padding: 5px;
  box-sizing: border-box;
  margin: 10px 30px;
  font-weight: bold;
}

.mybtn:hover {
  opacity: 0.9;
}

.join {
  background: #1b1464;
  color: #FFF;
}

.popup-close:hover {
  -webkit-transform: translate(50%, -50%) rotate(180deg);
  transform: translate(50%, -50%) rotate(180deg);
  background: red;
  text-decoration: none;
}

.right3 ul {
  padding: 0px;
  margin: 0px;
}

.right3 ul li {
  background-image: url('https://s33.postimg.cc/502ku2hsv/correct_sign.png');
  list-style: none;
  padding-left: 30px;
  background-repeat: no-repeat;
  background-position: left center;
  background-size: 15px;
}

.code {
  color: #23B14D;
  font-weight: 700;
}

.left3 {
  width: 40%;
  padding: 0 10px 0 0;
  box-sizing: border-box;
  min-height: 2px;
  float: left;
}

.right3 {
  width: 60%;
  padding: 0px;
  box-sizing: border-box;
  height: 310px;
  float: left;
  font-size: 17px;
}

.left3 img {
  width: 100%;
  margin-top: 0px;
}

.left3 {
  background: url('https://s33.postimg.cc/d5kms1ya7/player1.png') no-repeat center top / auto 100%;
}

.right3 p {
  margin: 0;
}

.popup-inner {
  display: flex;
  /*background: rgba(228,32,34,0.7); */
  background: red;
  border: 5px solid #FFF;
}

.preventclose {
  position: fixed;
  top: 0;
  width: 100%;
  height: 5px;
}

.left4 {
  width: 100%;
  float: left;
  padding: 0px;
  box-sizing: border-box;
}

.bbtitle {
  font-family: 'Poppins', sans-serif;
  color: #FFF;
  display: block;
  font-weight: bold;
  text-transform: capitalize;
  font-size: 26px;
  padding: 10px 10px 10px 0;
}

.right4 {
  width: 100%;
  float: left;
  color: #FFF;
  padding: 0 10px;
  box-sizing: border-box;
}

.popup-inner .left4 a {
  font-size: 21px;
  font-weight: bold;
}

.popup-inner .right4 a {
  font-size: 21px;
  font-weight: bold;
}

.firstlink {
  display: block;
  padding: 13px 10px 10px;
  background: none;
}

.endtext {
  padding: 10px;
  font-size: 13px;
  color: #999;
  font-weight: bold;
  margin-top: 21px !important;
  display: block;
  float: left;
}

.dollar25 {
  color: black;
  font-weight: bolder;
  text-shadow: 0px 0px 4px yellow;
}

.right3 p {
  padding: 5px;
  margin-top: 18px;
  font-size: 14px;
  text-align: justify;
}

.ifl-image {
  width: 80px !important;
}

@media(max-width:767px) {
  .left3 {
    width: 30%;
  }
  .right3 {
    width: 70%;
    height: 360px;
    padding: 0 10px;
  }
  .popup-inner {
    max-width: 600px;
  }
  .left3 img {
    width: 100%;
    margin-top: 18px;
  }
}

@media(max-width:550px) {
  .popup-inner {
    display: block;
  }
  .bbtitle {
    text-align: center;
    font-size: 22px;
  }
  .left3 {
    width: 100%;
    height: 200px;
    background-size: cover;
    background-position: center top;
  }
  .right3 {
    width: 100%;
  }
  .popup-inner {
    max-width: 400px;
  }
  .off {
    font-size: 60px;
  }
  .left3 img {
    width: 200px;
    margin-top: 18px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preventclose"></div>
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<div class="popup" data-popup="popup-1">
  <div class="popup-inner">
    <div class="left3"></div>
    <div class="right3">
      <div class="bbtitle">International Football League</div>
      <ul>
        <li>Want to win $100K?</li>
        <li>Want to win ownership of the IFL?</li>
        <li>Want to help pick team names?</li>
        <li>Want to help pick players for teams </li>
        <li>Want to help pick team logos?</li>
        <li>Want to help hire staff?</li>
        <li>Want to help fire staff?</li>
      </ul>
      <div class="buttons123">
        <a href="#" class="join mybtn">Join</a><a href="#" class="notnow mybtn">Not Now</a>
      </div>
      <p>Well there's no need to want anymore here's your chance. Just become a member of the International Football League for just <i class="dollar25">$25</i> to help call the shots.</p>
    </div>
    <a class="popup-close" data-popup-close="popup-1" href="#">x</a>
  </div>
</div>

Your feedback is valuable. Thank you in advance!

Answer №1

An alternative method would be to utilize localStorage in order to save a flag when a user visits your website. This information will persist across different browser sessions, but it's important to note that if the user switches browsers or clears their storage, the flag will be lost. If you want the flag to be available across various browsers and devices, consider storing it on a backend server and checking for its presence before displaying a popup.

Answer №2

If you're looking for a clever way to avoid showing the same popup to users multiple times, consider utilizing LocalStorage. By saving a boolean value in the storage when a user visits your site, you can easily determine whether or not to display the popup upon subsequent visits.

// Retrieve data from local storage
var hasPopupBeenDisplayed = localStorage.getItem('hasPopupBeenDisplayed');

jQuery(function() {
    // Close popup on button click
    jQuery('[data-popup-close]').on('click', function(e) {
        var targetedPopupClass = jQuery(this).attr('data-popup-close');
        jQuery('[data-popup="' + targetedPopupClass + '"]').fadeOut(350);
        e.preventDefault();
    });
});

jQuery(document).ready(function() {
    // Check if popupdisplayed value is null (user's first visit)
    if(hasPopupBeenDisplayed === null) {
        jQuery('.popup').show(0);
        var halfBrowserHeight = jQuery(window).height() / 2;
        
        // Show popup after scrolling halfway down the page
        jQuery(window).scroll(function() {
            var distance = jQuery(window).scrollTop();
            if (distance >= halfBrowserHeight && !hasPopupBeenDisplayed) {
                jQuery('.popup').show(0);
                // Store the display status in local storage
                localStorage.setItem('hasPopupBeenDisplayed', true); 
            }
        });
    }
});

Answer №3

To achieve this, it is essential to utilize cookies.

Javascript data is not maintained after a page reload. For instance:

window.createCookie = function(name,value,days) {
      var expires = "";

      if (days) {
        if (days === "midnight"){
          var today = new Date();
          var t = {
            d: today.getDate()+1,
            m:today.getMonth(),
            y: today.getFullYear()
          };
          var expiredate = new Date(t.y,t.m,t.d,00,01,00,00);
          expires = "; expires="+expiredate.toGMTString();

        }else{
          var date = new Date();
          date.setTime(date.getTime()+(days*24*60*60*1000));
          expires = "; expires="+date.toGMTString();
        }
      }
      // document.cookie = name+"="+value+expires+"; path=/"
    document.cookie = name+"="+value+expires+"; path="+window.location.pathname;
}

window.readCookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

window.eraseCookie = function(name) {
    createCookie(name,"",-1);
}

A cookie has an expiry... Using the functions above enables you to store, retrieve, and remove any cookie. The cookie will persist even after refreshing the page and will have a set expiration date.

Alternative technologies include "LocalStorage" and "WebStorage"

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

Is there a more intelligent approach to incorporating Bootstrap classes (or classes from another less.css file) into my less file through inheritance?

I am trying to find a more efficient way to integrate bootstrap classes into my less file. Currently, I am doing the following, but it has the disadvantage that not every "subclass" or connected class is inherited for my own control: .BWForm_form-control ...

Could you explain the meaning of the :host /deep/ selector?

Can you provide a simple explanation of what the :host /deep/ selector does? :host /deep/ .ui-autocomplete { width: 85%; } ...

Could someone explain how CSRF protection works with empty Flask-WTForms forms?

I have a query regarding csrf Cross-site Request Forgery Attacks in flask. After finding a helpful youtube video, here is what I learned: There was an incident where an email was changed by someone who was logged in through a specific path that allows up ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

Creating a unique post type in Wordpress

Currently, I am in the process of converting a Bootstrap one-page template into a WordPress template. My goal is to incorporate a custom post type that will display items in the services portfolio while maintaining the same CSS styling. Here is the code sn ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

Customizing Bootstrap Modal's backdrop CSS for a specific element

Upon opening a bootstrap modal, the background takes on a darker shade as seen here. I am looking to apply a CSS class that mimics this shading effect to a specific element. I prefer not to use any JavaScript for this task as it is purely about styling wi ...

Toggle checkboxes and submit form using dropdownlist with jQuery on change event

After successfully submitting the form using dropdownlist onchange method in jQuery, I encountered an issue when trying to enable checkboxes during the form submission with the same dropdownlist onchange event. The goal is for the checkboxes to be enabled ...

The controller is unable to accept JSON data from the JQuery.ajax function

I have thoroughly checked my web.xml and spring-servlet.xml files, but I couldn't find any issues. I then reviewed my Controller and .ajax() call, but still couldn't identify the problem. I experimented with using JSON.stringify, @RequestParam, a ...

Responsive Image Resizing with Bootstrap for Smaller Screens

I'm struggling to resize a responsive image in Bootstrap using the carousel example on their official website. <div class="container"> <div class="other-div"> .... </div> <div id="carouselExampleCon ...

What are the specific constraints for CSS within web components?

<html> <style> body { color: blue; } </style> <body> <h1>Styles!</h1> <p>someone created a very general selector</p> <isolated-stuff></isolated-stuff> </body> <s ...

jQuery is missing an essential component that is causing an error

I have successfully implemented the following JavaScript code and everything is working fine. However, I'm uncertain if my code is fully correct. I noticed that in my script, I only utilize success: function() without incorporating an error function. ...

Refresh a Div using JSON content with Struts2 Jquery Plugin

Is there a way to dynamically reload the content of a div with just a specific part of a JSON object in it? The code provided works perfectly, but it displays the entire JSON object within curly braces. I want only one variable from the object to be shown ...

jQuery Mobile using the old value instead of the new one

Sending a variable through a link: <a href="foo.php?var=101"> php </a> <a href="foo.php?var=102"> html </a> <a href="foo.php?var=102"> css </a> Upon reaching foo.php: <!-- this part is under data-role="page" !--> ...

What steps can be taken to modify this PHP script to send data via AJAX instead?

Currently, I have a contact form that only sends using PHP. I would like to modify it to send using AJAX instead. What is the simplest way to implement this change? <?php //If the form is submitted if(isset($_POST['submit'])) { //Check t ...

Develop a distinctive JavaScript solution that enables an image to appear in fullscreen upon loading the page, and then smoothly fade away after precisely

I have been trying to incorporate a feature on my Shopify frontage website where our logo appears fullscreen and then fades away or disappears after a few seconds, allowing people to access the rest of the website. However, I am facing difficulty in making ...

What is the best way to display a chosen item in a text input field?

https://i.stack.imgur.com/Qe5Ds.png Looking to create a similar design, but lacking the necessary expertise. What steps should I take or what is the specific term for this style? Seeking assistance in implementing this using jQuery, PHP, or JavaScript. A ...

Tips for Preventing the Previous Value from Being Displayed When Changing the Option in a Select Field Using the Live Change jQuery Function

In the table I am using, the select option is filled based on the number of rows in the table. I have implemented a live change function in jQuery to track changes and store them in a variable. However, when clicking the next option, it returns the previ ...

Steps to create a responsive iframe for Slideshare

Recently, I included a slideshare iframe presentation on my webpage. Here is the code snippet I used: <iframe src="//www.slideshare.net/slideshow/embed_code/key/HQoiz6GR1oLe1n" width="860" height="600" frameborder="600" marginwidth="0" marginheight="0 ...

What are the steps to create a unique popup div effect with jQuery?

Upon clicking the icon on this page, a mysterious div appears with information. I'm completely baffled by how they achieved this cool effect using css/jQuery tools. Can anyone shed some light on the mechanism behind this? ...