When a user closes a
, hide that
on all site pages

前端 未结 12 940
忘了有多久
忘了有多久 2020-12-15 02:49

I\'ve developed a couple of alert boxes that display on all site pages.

The user is able to close each box separately:

12条回答
  •  误落风尘
    2020-12-15 03:48

    Use localStorage().

    Local storage is per origin (per domain and protocol)

    • On click of DIV close, you can get the current time-stamp
    • Add number of hours (24) to that time-stamp
    • Store that value in localStorage as localStorage.setItem('desiredTime', time)
    • Check current time-stamp with that stored time-stamp localStorage.getItem('desiredTime'), based on that show/hide

    jQuery

    $(document).ready(function(){
            //Get current time
            var currentTime = new Date().getTime();
            //Add hours function
            Date.prototype.addHours = function(h) {    
               this.setTime(this.getTime() + (h*60*60*1000)); 
               return this;   
            }
            //Get time after 24 hours
            var after24 = new Date().addHours(10).getTime();
            //Hide div click
            $('.hide24').click(function(){
                //Hide div
                $(this).hide();
                //Set desired time till you want to hide that div
                localStorage.setItem('desiredTime', after24); 
            });
            //If desired time >= currentTime, based on that HIDE / SHOW
            if(localStorage.getItem('desiredTime') >= currentTime)
            {
                $('.hide24').hide();
            }
            else
            {
                $('.hide24').show();
            }
    });
    

    HTML

    DIV-1
    DIV-2

    Things to note

    • You can use $.cookie as well, but that's an older approach now.
    • with class hide24 will be hidden only.
    • Make sure that you put this code in general JavaScript, which loads on every HTTP request of your website.
    • For localStorage, you should have HTML5 browsers.

    Web Storage HTML5

    Hope this helps.

提交回复
热议问题