Javascript Course


A cookie is a small piece of information (a string with key=value pair) stored to the user’s computer. Each time a computer requests a page with the same browser, it will send the cookie too. It can be accessed any time the viewer returns to your site, provided the cookie hasn’t been deleted or expired.
If the viewer doesn’t accept cookies, then a cookie won’t be able to be set or used later.
Cookies have some significant limitations:


Creating cookie

To create / set a cookie, just assign the name and value to document.cookie property, in the following format:

document.cookie = 'name=value';

- A cookie can also have some optional parameters, but only the name and the value are required, the other parameters are optional; described below:

You can’t have spaces, commas, or semicolons inside the cookie string, you should allways pass the value part of the string through encodeURIComponent() to make sure you use URI-safe characters.


nume=valoare - the name and value stored in cookie (the name should contain only letters, numbers, and _ ). - Example:
var val_c ='value';
document.cookie ='some_name='+ encodeURIComponent(val_c);
- The encodeURIComponent() method is applyed to encode the characters like ( =;.).
expires=date - 'date' is a string with the date-time on which this cookie expires.
This must be converted in milliseconds, in GMT format: Wdy, DD-Mon-YYYY HH:MM:SS GMT.
If the expires (or max-age) is nod specified, the cookie will disappear when the browser window is closed.
- Example:
var one_week = 7*24*60*60*1000; //an week in milisecunde
var exp_dt = new Date();
exp_dt.setTime(exp_dt.getTime() + one_week);
document.cookie ='food=fruits; expires='+ exp_dt.toGMTString();
- The toGMTString() method converts the Date object to a string in GMT format.
max-age=seconds - sets the time of existence of the cookie in seconds, after which period the cookie will expire.
It can be used instead of expires, and is more simply.
If neither expires nor max-age specified it will expire when the browser window is closed.
- Example:
var one_week = 7*24*60*60; //an week in secunde
document.cookie ='food=fruits; max-age='+ one_week;
path=path - determines the pages in the site where that cookie can be used.
If not specified, the cookie can be accessed in the directory and subdirectories of the page where it is set.
- Example:
//cookie 'food' is available on all pages in the '/blog' directory (including subdirectories)
document.cookie ='food=fruits; path=/blog';

//cookie 'food' is available on all pages in the 'javascript/test' directory (including subdirectories)
document.cookie ='color=blue; path=/javascript/test';
- To set a cookie available in all the pages of your website, add the root path '/' ( path=/ ).
domain=domain_name - the domain or subdomain that can read that cookie.
If not specified, this defaults to the host portion of the current document location.
- Example:
//cookie 'food' available on all pages of the site: coursesweb.net (including subdomains)
document.cookie ='food=fruits; path=/; domain=coursesweb.net';

//cookie 'color' available on all pages of subdomain: 'bfie.marplo.net/'
document.cookie ='color=blue; path=/; domain=bfie.marplo.net';
secure - if set, the browser will send that cookie over HTTPS only. - Example:
var one_week = 7*24*60*60; //one week in secunde
document.cookie ='food=fruits; path=/; secure; max-age='+ one_week;

Function to create cookie in JavaScript

The following example shows a useful JavaScript function to create cookie with necessary parameters.
function setCookie(name, value, maxage, path){
 var maxage =(!maxage) ? '' :'; max-age='+ maxage;
 var path =(!path) ? '' :'; path=' + path;
 document.cookie = name + '='+ encodeURIComponent(value) + maxage + path;
}
- This function can be used as in this code:
//define a cookie available one week on all pages
var m_age = 7*24*60*60;
setCookie('a_name', 'some-value', m_age, '/');

Reading cookies

To read cookie, you need to get the value of the document.cookie property from the browser.
var mycookie = document.cookie;
document.cookie returns a string with all cookies available in the page. A string like this:
name1=value1; name2=value2; name3=value3
Where name1, name2, name3 are the name of each cookie, and value1, value2, value3 are their values.

- Example:
<h4>Example document.cookie</h4>
<p>If you click on the button, it will display the value returned by <em>document.cookie</em>.</p>
<button id='btn1'>Cookie</button>
<blockquote id='resp'>#resp</blockquote>

<script>
document.getElementById('btn1').addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML = document.cookie;
});
</script>
To read a specific cookie, you have to parse the string returned by document.cookie.
To simplify finding a value from a cookie, you can use the getCookie() function from the following JS code:
function getCookie(name){
 var re ='';
 var str_c =' '+ document.cookie +';'; //puts the cookie string between a space and a ;
 var name =' '+ name +'='; //to look for what it's between name and =
 var start_c = str_c.indexOf(name); //where the name starts
 var end_c;
 if(start_c != -1) { //if contains the specified name
 start_c += name.length; //where the value starts
 end_c = str_c.indexOf(';', start_c); //where the value ends
 re = decodeURIComponent(str_c.substring(start_c, end_c)); //the value
 }
 return re;
}

var val_c = GetCookie('cookie_name');
document.write(val_c); //Displays the value of the cookie, or an empty string ''

Deleting cookie

To delete a cookie, simply have it expire immediately by setting 'max-age' with a negative value, or expire to some time before the current time.
If you specified a domain and path for the cookie, you have to do the same when you delete it:
//deletes the cookie from name
//path is required only if it was used when the cookie was created
function delCookie(name, path){
 var path =(!path) ? '' :'; path=' + path;
 var two_d = 2*24*60*60; //two days in seconds
 document.cookie = name + "=bye; max-age=-" + two_d + path; 
}
- Just call the delCookie('cookie_name') function.

Full example of using cookies

To understand better what cookies do, how to create and use cookies, study the following example.
It's a more complex example, includes a script with several functions that contain many of the elements presented in this lesson.
The purpose of this example is to understand how the cookies works. It contains a JavaScript script that has functions for working with cookies.
In a column there are input fields to write preferences that will be sent to the JS script that stores them in cookie, and the second column contains a button to display the preferences saved in cookies, and another button to delete cookies.
- Here is the complete code, click on the button below to test it:
<style>
#add_fav, #show_fav {
display:inline-block;
font-size:18px;
margin:5px 8px;
padding:4px 5px;
}
#add_fav {
background:#dee0fe;
width:350px;
}
#show_fav {
border:1px solid #000;
background:#b0eeb0;
vertical-align:top;
width:250px;
}
#show_fav em {
font-weight:700;
}
#set_c {
display:block;
margin:8px auto;
}
</style>

<h4>Example JS script with cookie</h4>
<p>Fill in the text boxes at the left and then click 'Save Favorite', it calls the 'setCookie()' function that will store them in cookies that will expire in five days.<br>
 Click on "Show Favorites", it calls the "getCookie()" function, this will get the data from cookies and will display the preferences you have added.<br>
 - If you close this window and reopen it, when you click on "Show Favorites", it will display your preferences added earlier.<br><br>
Then clck "Delete cookie" button, it calls the delCookie() function that deletes these cookies.<br>
The next click on "Show Favorites" will display nothing because the cookies with the preferences where deleted.</p>
<div id='add_fav'>
Favorite Color: <input type='text' id='color' maxlength='40' /><br>
Favorite fruits: <input type='text' id='fruits' maxlength='40' /><br>
Favorite quote: <input type='text' id='quote' size='35' maxlength='80' /><br>
 <em id='resp'></em>
<button id='set_c'>Save Favorite</button> <em id='resp'></em>
</div>
<div id='show_fav'>
<button id='get_c'>Show Favorites</button> &nbsp; 
<button id='del_c'>Delete cookie</button>
<div>
Favorite Color: <em id='c_color'></em><br>
Favorite fruits: <em id='c_fruits'></em><br>
Favorite quote: <em id='c_quote'></em>
</div>
</div>

<script>
//sets cookie name with value (available 5 days on all the pages)
function setCookie(name, value, maxage, path){
 var maxage = 5*24*60*60; //5 days in seconds
 document.cookie = name + '='+ encodeURIComponent(value)+'; max-age='+ maxage +'; path=/';
}

//returns the value of the cookie from name, or empty string
function getCookie(name){
 var re ='';
 var str_c =' '+ document.cookie +';'; //puts the cookie string between a space and a ;
 var name =' '+ name +'='; //to look for what it's between name and =
 var start_c = str_c.indexOf(name); //where the name starts
 var end_c;
 if(start_c != -1) { //if contains the specified name
 start_c += name.length; //where the value starts
 end_c = str_c.indexOf(';', start_c); //where the value ends
 re = decodeURIComponent(str_c.substring(start_c, end_c)); //the value
 }
 return re;
}

//deletes the cookie from name
function delCookie(name){ 
 var two_d = 2*24*60*60*1000; //two days in seconds
 document.cookie = name + '=bye; path=/; max-age=-'+ two_d; 
}

//array with names for cookie (the same with input id)
var arr_co =['color', 'fruits', 'quote'];

//the click on #set_c saves data in cookie
document.getElementById('set_c').addEventListener('click', (ev)=>{
 for(var i=0; i<arr_co.length; i++) setCookie(arr_co[i], document.getElementById(arr_co[i]).value);
 document.getElementById('resp').textContent ='- Data saved';
});

//the click on #get_c displays data from cookie
document.getElementById('get_c').addEventListener('click', (ev)=>{
 for(var i=0; i<arr_co.length; i++) document.getElementById('c_'+arr_co[i]).textContent = getCookie(arr_co[i]);
});

//the click on #del_c Delete data saved in cookie
document.getElementById('del_c').addEventListener('click', (ev)=>{
 for(var i=0; i<arr_co.length; i++){
 delCookie(arr_co[i]);
 document.getElementById('c_'+arr_co[i]).textContent ='';
 }
});
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Cookies

Last accessed pages

  1. PHP getElementById and getElementsByTagName (49471)
  2. Mysql SELECT JOIN tables on two different Databases (4498)
  3. jQuery UI draggable - Drag elements (11448)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142520)
  5. Using the Bone Tool (4253)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)