3

I want to show popup just once per session which expire after some time. Can someone help me?

function PopUp(){
    $('.home-popup').fadeIn(500);
}

setTimeout(function(){
  PopUp();
},1000); // 1000 to load it after 1 second from page load

$('.close-popup-btn').click(function() {
    $('.popup').fadeOut(300);
});
Rama
  • 3,222
  • 2
  • 11
  • 26
Bane
  • 49
  • 1
  • 1
  • 9
  • Are you looking to have the popup fade out automatically? In that case, you can also set a callback function on the fadeIn to occur when that has completed, to fade out after a given interval. If you're looking to make sure the popup doesn't continue to pop up during a given session, set a cookie. – Snowmonkey Jan 25 '17 at 16:56
  • @Snowmonkey I have close button for popup fadeOut, not closing automatically. How to set cookie, some example? – Bane Jan 25 '17 at 16:59

2 Answers2

9

You could use localstorage for this as well. To set a storage item: localStorage.setItem('myPopup','true'); and to check for it you could do something like this:

var poppy = localStorage.getItem('myPopup');

if(!poppy){
    function PopUp(){
        $('.home-popup').fadeIn(500);
    }

    setTimeout(function(){
        PopUp();
    },1000); // 1000 to load it after 1 second from page load

    $('.close-popup-btn').click(function() {
        $('.popup').fadeOut(300);
    });
    localStorage.setItem('myPopup','true');
}
oompahlumpa
  • 495
  • 2
  • 10
  • It does not have expiration. But if you want it to clear out when the user closes the browser or tab, you could do: `$(window).bind('beforeunload', function(){ localStorage.removeItem('myPopup'); });` – oompahlumpa Jan 25 '17 at 17:23
  • I personally use this for an email collection popup in which I only want my users to see it once. And not get bombarded with it and this works very nicely. If a specific expiration date is necessary you will have to use a cookie. LocalStorage is quick and easy. – oompahlumpa Jan 25 '17 at 17:27
  • Do you know or have some example how i can do this with cookie? – Bane Jan 26 '17 at 10:34
  • Are your pages PHP? – oompahlumpa Jan 26 '17 at 16:06
  • 1
    Actually refer to Antony's post below. He has a pretty easy way of using Javascript to set cookies. – oompahlumpa Jan 26 '17 at 16:07
3

I would set a cookie with the popupSent value on the first visit, and check if the cookie exists before calling the PopUp function. Here is a rough implementation with the cookie helper functions from here: Set cookie and get cookie with JavaScript

function PopUp(){
    $('.home-popup').fadeIn(500);
    createCookie('popup','1');
}
if(readCookie('popup')){
    // 1000 to load it after 1 second from page load
    setTimeout(PopUp,1000); 
}
$('.close-popup-btn').click(function() {
    $('.popup').fadeOut(300);
});
Community
  • 1
  • 1
Antony
  • 1,253
  • 11
  • 19