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

Navigating to an offline HTML webpage using JavaScript in a PhoneGap application

I am currently developing a phonegap application. I am attempting to create a login feature where upon clicking the submit button on the Login.html page, I should be directed to a local HTML file. Login.html <tr> <td>&nbsp;</td> ...

What is the best way to halt a specific function in jQuery?

I recently developed a website for my photographer friend, and I implemented a feature where the home page is initially blurred. Visitors can click a button to unblur the content. While the functionality works smoothly, there's one issue - every time ...

Ways to remove the initial row of inline-block divs

My webpage is filled with inline-block divs that are contained within a larger div like so: <div class="container"> <div class="text">Text 1</div> <div class="text">Text 2 ... rest of the nu ...

Enhancing user experience with VideoJS player overlay buttons on mobile devices

I am currently using VideoJs player version 4.2. When I launch a videojs player on Safari browser in an iOS device, it defaults to native controls. However, when I pause the player, overlay buttons (links to navigate to other pages) are displayed on the v ...

Update the formatting of the dates in the dateRangePicker

Utilizing a dateRangePicker, I am receiving dates in the format "mm-dd-yyyy". Below is my HTML code: <input type="text" name="TextDate" value="10/24/1984" /> Here is the script being used: <script> $(function() { $(&apos ...

How can you add a new div directly after the parent div's content and display it in-line?

I have a banner that stretches to fill the width completely. Inside this main div, there is another smaller div measuring 30px in size positioned at the end. The nested div contains a close icon background image, and upon clicking it, the entire banner get ...

Conditions in Apache mod_rewrite

Having trouble with Apache's module rewrite (creating browser-friendly URLs). My goal is to redirect every request to a specific PHP document if it contains a certain string: RewriteBase /folder/directory/ RewriteCond %{REQUEST_FILENAME} !-f RewriteC ...

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...

Refine results by searching through the text contained in the elements of every div

I recently came across a helpful fiddle that allows text to be hidden based on what is entered into a search box. However, I am struggling to apply this method to a div that contains multiple elements. Is there a way to modify the jQuery in the provided fi ...

EaselJS - Utilizing multiple canvases with varying frame rates

Currently, I am exploring EaselJS by creating two animation instances using sprite sheets on two separate canvases positioned at different locations but with the same z-index. The issue I am facing is that these instances are not layered properly. My setup ...

Tips for preventing menu flickering caused by overflow during CSS animations

I recently created a vertical menu with an interesting underline effect that appears when hovering over the menu items. Even though the snippet initially failed to execute, I discovered this cool hover effect (taken from here) which I wanted to implement: ...

Wait for the page content to finish loading before loading the Facebook Like Box

I am currently working on a method to delay the loading of the Facebook Like Box until after the page content has been fully loaded. My approach involves using AJAX, but I have encountered mixed results thus far. Initially, I used the following code snippe ...

Encountering a parser error while invoking JasperReport via AJAX in a Spring MVC environment

I am using jQuery AJAX to call an endpoint and generate a JasperReport with Spring MVC. My goal is to view the generated report as a PDF in a new browser tab. However, I encountered a problem where I am receiving a parsererror with a conversion failure fro ...

Exclusive Chrome Bug Found in Form Tag

My webpage functions flawlessly on IE 7, 8, and 9, Firefox, Safari, and Opera. However, when I view it on Chrome, the positioning of the DIV containing the form is not always correct. If I remove the form tag, the issue goes away. There are no floats, only ...

Transforming a Bootstrap Background Image to a Captivating Video Display

Here is the CSS code snippet that I'm having trouble with: .masthead { position: relative; width: 100%; height: auto; min-height: 35rem; padding: 15rem 0; background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 75% ...

Run a JavaScript function in 5 seconds

I'm looking to execute this function after a 5-second delay: $(document).ready(function() { $("#signInButton").trigger('click'); }); Your assistance is greatly appreciated. ...

What could be causing my sticky positioning to not function properly when I scroll outside of the designated

My website is organized into sections, with each section corresponding to a hyperlink in the navigation menu. I've applied the CSS property position: sticky to my navbar, which works as expected within the section bounds. However, I want my red navbar ...

Designing with Bootstrap 4 involves incorporating a button that uses the data-toggle attribute set to "collapse" along with an href anchor linked to

I have attempted to link to an ID while also triggering a data-toggle collapse: <a href="#id" data-toggle="collapse" data-target="#collapseTwo" class="btn btn-primary" title="Something cool">Something very cool</a> for linking to this specif ...

When using Jsoup, make sure to nest the <div> tag within an <a>

As per the findings in this response: Referring to HTML 4.01 guidelines, <a> elements are limited to inline elements only. Since a <div> is a block element, it should not be placed within an <a>. However... In HTML5, <a> elements are all ...

Modify the database value linked to an <input> element each time its value is modified

I attempted to create something similar to the example provided here $(document).ready(function(){ $('input[type=text]').keyup(function(){ var c=0; var a=$(this).attr('name'); //a is string //if var a change.. ...