X

LATEST #JQUERY NEWS

Set/Get/Delete Cookies with jQuery


There are a lot of plugins you can use to set, get, and delete cookies using jQuery, but there’s also a fairly simple code that will achieve all three of those actions without the need for a heavy plugin. Check out the snippets below:

Set cookies:

function setCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + '=' + escape(value) +
        ((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
        ((path) ? ';path=' + path : '') +
        ((domain) ? ';domain=' + domain : '') +
        ((secure) ? ';secure' : '');
}

Get cookies:

 function getCookie(name) {
     var start = document.cookie.indexOf(name + "=");
     var len = start + name.length + 1;
     if ((!start) & amp; & amp;
         (name != document.cookie.substring(0, name.length))) {
         return null;
     }
     if (start == -1) return null;
     var end = document.cookie.indexOf(';', len);
     if (end == -1) end = document.cookie.length;
     return unescape(document.cookie.substring(len, end));
 }

Delete cookies:

function deleteCookie(name, path, domain) {
    if (getCookie(name)) document.cookie = name + '=' +
        ((path) ? ';path=' + path : '') +
        ((domain) ? ';domain=' + domain : '') +
        ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

Recently Published

article image
»

7 Responsive jQuery Dropdown Menu Plugins

Dropdown Menu Plugins Dropdown menus are mostly used for website ...

article image
»

20 Stylish and Modern jQuery Tooltip Plugins

jQuery Tooltip Plugins Tooltips are a great option for showing extra ...

article image
»

15 Newest jQuery plugins for responsive website

Due to the proliferation of smartphones and tablets, responsive ...

article image
»

How to use Redux with jQuery

State management is one of most integral parts of any software and a ...

article image
»

Fade HTML Table Row on Hover Using jQuery

HTML tables are the ideal choice for displaying data in tabular form. ...

article image
»

Drag and Drop HTML Table Rows Using jQuery

HTML tables are the preferred UI option for displaying data. Sorting, ...

article image
»

Top 5 Best JavaScript Template Engines

Template engines help in the decoupling of HTML and JavaScript code ...

article image
»

3 jQuery/JavaScript Plugins for Push Notifications

Push notifications started from the mobile business but this ...

article image
»

Create Smooth Animation Using jQuery’s “stop()”

Making Quick Work jQuery’s animate() method is a quick way to ...