Friday, 13 January 2017

Jquery set cookie and get cookie



HTML

<ul class="nav metismenu" id="side-menu">
    <li>
        <a href="#">Dashboards</a>
        <ul class="nav nav-second-level collapse">
            <li><a href="#A">A</a></li>
            <li><a href="#B">B</a></li>
            <li><a href="#C">C</a></li>
            <li><a href="#D">D</a></li>
            <li><a href="#E">E</a></li>
        </ul>
    </li>
</ul>


CSS

.active a {
    color: green;
}

a {
    text-decoration: none;
}

SCRIPT

< script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" > < /script>

<script>
    //document.cookie="active=#C";
    $(document).ready(function() {
        if (typeof(getCookie("activeLi")) != "undefined" && getCookie("activeLi").length > 0) {
            $('#side-menu ul a[ href=' + getCookie("activeLi") + ']').parent().addClass("active");
        }
        $("#side-menu ul a").click(function(a) {
            removeActive();
            $(this).parent().addClass("active");
            setActiveCookie(this.getAttribute("href"));
        });
    });

function removeActive() {
    $("#side-menu ul li").each(function(li) {
        $(this).removeClass("active");
    })
}

function setActiveCookie(active) {
    //document.cookie="activeLi="+active;
    var d = new Date();
    d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); // expire in 30 days
    var expires = "expires=" + d.toUTCString();
    document.cookie = "activeLi=" + active + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

</script>


No comments:

Post a Comment