cookiesalert

Cookie alert at bottom


I want a alert at the bottom of the screen that says that the website is using cookies (and it only needs to be shown to new users). It needs to stay at the bottom if you scroll down too. I don't know how to do it, because I am a self-learning person and I am just starting learning how to code. Thanks for the help.


Solution

  • Part 1: HTML & CSS

    We need to add the alert panel into the bottom of the page. To style this panel, we should use CSS. This panel also has the confirmation button. When the user clicks the confirmation button, we set a cookie in the browser and never show the panel again.

    <div class="bottom" id="alert">
        This website uses cookies
        <button onclick="accpetCookie()">
            Click here to accept cookies
        </button>
    </div>
    <div class="scroll">
        website content
    </div>
    

    Here is the styling for the CSS classes:

    .bottom {
        position: fixed;
        bottom: 0;
        width: 100%;
        background: #ccc;
        color: #fff
    }
    
    .scroll {
        min-height: 1500px;
    }
    

    Part 2: JavaScript

    <script>
        // if user has already checked the confirmation button
        // the alert panel should be hidden.   
        if (getCookie('accepted') === 'yes') {
            document.getElementById("alert").style.display = "none";
        }
    
        // user clicks the confirmation -> 
        // set a cookie with name: 'accepted' and value: 'yes'
        function accpetCookie() {
            setCookie('accepted', 'yes', 100);
        }
        
    
        // code from: http://stackoverflow.com/a/4825695/191220
        // set cookie method
        function setCookie(c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
    
            var c_value = escape(value) + 
                ((exdays == null) 
                    ? "" 
                    : "; expires=" + exdate.toUTCString());
    
            document.cookie = c_name + "=" + c_value;
        }
    
        // get cookie method   
        function getCookie(c_name) {
            var i, x, y, ARRcookies = document.cookie.split(";");
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == c_name) {
                    return unescape(y);
                }
            }
        }
    </script>
    

    Check the JsFiddle page for a live demo.