How to hide div serverside by reading cookie

I am using following a tutorial from here: http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

This is the script I use:

Read More
<script type="text/javascript" language="javascript"> 
        $(function() {
            // SETUP:
                // When the info banner is clicked:
                $('#setup').click(function() {
                    $('#intro').css("display","none");
                    $.cookie('intro', 'collapsed');
                });
            // COOKIES
                // Info banner state
                var intro = $.cookie('intro');

            // READ THE COOKIES
                if (intro == 'collapsed') {
                  $('#intro').css("display","none");
                };
        });
</script> 

The script hides the following div as the cookie is read:

<div class="feedback attention" id="intro">
            Text goes here
            <a id="setup" href="#">Ok I get it, please hide this</a> 
</div>

Everything work great but when the page loads the div is shown for a split second. I guess the solution is to present two different pieces of markup serverside according to the cookie info. I have no idea how to go about this.

Related posts

Leave a Reply

4 comments

  1. On page load, you could use php to check the cookie, and then add a hidden class. Something like <div class="<?= $_COOKIE['intro'] == 'collapsed' ? 'hidden':'' ?>">

    Edit:

    In CSS then, you can add something like .hidden { display: none; } and use jQuery to add or remove that class.

  2. if you are using PHP:

    <?php if($_COOKIE['intro'] != 'collapsed'){ ?>
    
    <div class="feedback attention" id="intro">
                Text goes here
                <a id="setup" href="#">Ok I get it, please hide this</a> 
    </div>
    
    <?php } ?>
    

    To completely remove the div rather than just hide it.

  3. check $_COOKIE array for ‘intro’

    if ($_COOKIE['intro'] == 'collapsed') 
    //...
    

    simply, add some kind of “hidden” class to the div, or specify it like style="display: none;"

    //edit
    actually, by adding the “style” attribute you ensure that the div is not displayed as soon as get parsed, while using “class” property might cause interval while waiting for CSS file.

    thus

    <div<?= ($_COOKIE['intro'] == 'collapsed') ? ' style="display: none"' : '' ?>> ..</div>
    

    is best here.