100+ JavaScript

Loop In JS Function localStorage Drag Drop Object get set

Asynchronous JS

Callback Promises

Web API

Web API Intro Cookie Fetch API

JS PDF

Basic Pdf

Toast.js

Basic Toastr

Cookie🍪

A cookie is a small piece of data that a website stores on a user's devic (computer, smartphone, tablet etc). When they visit the site. This data is used to remember information about the user. This way, the website can make things easier for you, like remembering your favorite settings or what you were looking at before.

Why is a Cookie Important?

  • User Experiance: Cookie enhance the user experiance by remembering login details, language preferences, items in a shopping cart, and other personalized settings. This means user don't have to re-enter infomation every tim they visit the site.
  • Session Management: Cookies also help websites remember you when you visit different parts of the same site. Imagine you log in to your favorite game. A cookie helps the game remember that you're logged in, so you don't have to keep typing your password every time you go to a new level.

In the example to follow, we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he/she will be asked to fill in his/her name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he/she will get a welcome message.
For the example we will create 3 JavaScript functions:

  • checkCookie()
  • getCookie()
  • setCookie()
Example:
                            
    function setCookie(cname,cvalue,expires){
        //const d=new Date().getTime(); 
    
        document.cookie=cname+"="+cvalue+";"+"max-age="+expires+";path=/";
    
    }
    
    function getCookie(cookiename){
        console.log(cookiename);
        let name=cookiename+"=";
        let ca=document.cookie.split(";");
    
        for(let i=0;i< ca.length;i++){
            let c=ca[i];
    
            while(c.charAt(0)==" "){
                c=c.substring(1);
            }
            if(c.indexOf(cookiename)==0){
                return c.substring(cookiename.length,c.length);
            }
        }
    
    
        return "";
    
        
    
    }
    
    function checkCookie(){
        let user=getCookie("username");
        if(user!=""){
            alert("Welcome again "+user);
        }
        else{
    
            //prompt() is called, it pauses the executions of the script and display a dialog box.
            let input=prompt("Eneter Username: ");
    
            if(input!="" && input!=null){
                setCookie("username",input,30*86400);
            }
    
            
        }
    
    }
    
    checkCookie();