Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show div once a day

<div class="ads">Some text</div>

Want to:

  1. show this block once a day per visitor (no registration) (hidden by default, cookie check, what should be used?)
  2. if block already was shown today, then don't show it today anymore
  3. if block was shown yeasterday and one day is past, then show it again (how to check properly that the one day is past?)

How can I do this?

Site-examples with this feature:

http://premiumpixels.com

http://365psd.com

like image 979
James Avatar asked Nov 15 '11 06:11

James


2 Answers

I've created example code that implement the requirement using cookie:

It depend on jQuery and Cookie plugin.

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
        <script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/raw/master/jquery.cookie.js"></script>
        <script type="text/javascript">                                         
        $(document).ready(function() {
            if( $.cookie('showOnlyOne') ){
                //it is still within the day
                //hide the div
                $('#shownOnlyOnceADay').hide();
            } else {
                //either cookie already expired, or user never visit the site
                //create the cookie
                $.cookie('showOnlyOne', 'showOnlyOne', { expires: 1 });

                //and display the div
                $('#shownOnlyOnceADay').show();
            }
        });
        </script>     
    </head>
    <body>
        <div id="shownOnlyOnceADay">
            This text should only be shown once a day!
        </div>
    </body>
</html>

Tested it by changing system date.

like image 125
ariefbayu Avatar answered Oct 13 '22 07:10

ariefbayu


You can just use some code like this, assuming you always start off with your div having its style display property set to none:

if(localStorage.last){
    if( (localStorage.last - Date.now() ) / (1000*60*60*24) >= 1){ //Date.now() is in milliseconds, so convert it all to days, and if it's more than 1 day, show the div
        document.getElementById('div').style.display = 'block'; //Show the div
        localStorage.last = Date.now(); //Reset your timer
    }
}
else {
    localStorage.last = Date.now();
    document.getElementById('div').style.display = 'block'; //Show the div because you haven't ever shown it before.
}

Reference

like image 24
Some Guy Avatar answered Oct 13 '22 07:10

Some Guy