Search code examples
javascripthtmlcookiesonclickshow-hide

Show/Hide div on button click and save Cookies


I use This javascript codes for cookies and show/hide;

$(document).ready(function () {

        if (Boolean(readCookie('hide'))) {
            $('.pop-up').hide();
            $('.pop-up').fadeOut(1000);
        }
        $('.close-button').click(function (e) {

            $('.pop-up').fadeOut(700);
            $('#overlay').removeClass('blur-in');
            $('#overlay').addClass('blur-out');
            e.stopPropagation();

            createCookie('hide', true, 1)
            return false;
        });

        function createCookie(name, value, days) {
            if (days == 1) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires2 = "";
            document.cookie = name + "=" + value + "; expires=" + expires + "; path=/";

          //  $.cookie(name, value, { expires: days });
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name, "", -1);
        }

    });

I need 10 buttons on same page but I can't. Because if I click close-button (X) all buttons hides. I need one by one hide.

I try to change name and value but unsuccessful.

This is HTML;

<div id="overlay" class="cover blur-in">
    <div class="content"></div>
</div>
<div class="row pop-up">
    <div class="box small-6 large-centered">
        <a href="#" class="close-button">✖</a>
        <h3 class="popup">Welcome</h3>
        <p>info </p>
        <p>info</p>
        <a href="#" class="button">press for facebook</a>
    </div>
</div>

This is jsfiddle for this code


Solution

  • Your jsfiddle doesn't seem to be working (blank), but the general idea would be to loop through all elements with close_button class and to add a listener to each, something like this:

    $('.close-button').each(function(i, obj) {
         $(this).click(function (e) {
             $('.pop-up').eq(i).fadeOut(700);
             $('#overlay').removeClass('blur-in');
             $('#overlay').addClass('blur-out');
             e.stopPropagation();
             return false;
         })
    });