Add a simple popup in your website and WordPress

Popups are useful in almost every website, as long as you do not abuse. I prefer to add a popup when a user scrolls half of a page, otherwise it might have a backfire effect. Everybody knows all these annoying popups that shows immediately after the page is loaded. You just want to close this website as fast as possible.

CSS

Place it in your styles.css

#popup {
  position: fixed;
  display: none;
  top: 42%;
  left: 41%;
  background-color: #fff;
  border: 1px solid #eee;
  padding: 20px;
  z-index: 99999;
  color: #222;
  -webkit-box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);
  -moz-box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);
  box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);
}
 
#popup .close-button {
    position: absolute;
    right: -7px;
    top: -10px;
    cursor: pointer;
    width: 10px;
    height: 10px;
    background-color: #ff4500;
}

Classic Popup

(append to body with JS on all pages)

jQuery(document).ready(function($){
 
if (sessionStorage.getItem('popup') !== 'true') {
$('body').append('<div id="popup">Follow me on...<div class="close-button"><i class="fa fa-times-circle fa-lg"></div></div>')
sessionStorage.setItem('popup','true');
} 
$(window).scroll(function () { 
  if ($(window).scrollTop() > $('body').height() / 3) {
    $('#popup').show();
  } 
});
$('#popup .close-button').on('click',function(){
$('#popup').remove();
});
});

This adds popup immediately after the page is loaded. To add content change after append().

Alternative

(exists in HTML already)

jQuery(document).ready(function($){
 
if (sessionStorage.getItem('popup') !== 'true') {
    $(window).scroll(function () { 
  if ($(window).scrollTop() > $('body').height() / 3) {
    $('#popup').fadeIn(), '3000';
  } 
});
sessionStorage.setItem('popup','true');
}
 
$('#popup .close-button').on('click',function(){
$('#popup').remove();
});
 
});

This one just calls the id of your div which already exists in your page. To add content you need to find where #popup is located (index.html, header, footer etc.).
For example in WordPress you can locate it in footer.php and with a simple IF you can set where to display the popup.

sessionStorage vs localStorage

In our example, sessionStorage will store your popup for the current TAB in your browser. If you open an article in a new tab from the same website, the popup will appear again.

localStorage on the other hand, will store your popup on your browser cache. In other words, your popup will appear once until a user delete its’ cache from the browser.

What do you think? Do you know better solution for a simple popup?

Leave a Reply