Monday, June 8, 2015

JavaScript Tutorial 3

JavaScript Cookies

A cookie is often used to identify a user.

What is a Cookie?

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.
Examples of cookies:
  • Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
  • Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie

Create and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to  fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.
First, we create a function that stores the name of the visitor in a cookie variable:
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;
}
The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.
In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.

Get a Cookie Value

Then, we create another function that returns the value of a specified cookie:
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
  {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
The code above uses the indexOf() method to search for a cookie name inside the document's cookie string.
The first indexOf() method will return the position where the cookie is found. The " " + and +"=" is added so that the method don't find names or values containing the name.
If the method returns -1, the cookie may still exist at the very beginning of the cookie string. To eliminate this, another search is added, this time without the " " +.

Check a Cookie Value

Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
All together now:
<!DOCTYPE html>
<head>
<script>
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
    {
    c_end = c_value.length;
    }
  c_value = unescape(c_value.substring(c_start,c_end));
  }
return c_value;
}
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;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
Some explanation about this code:

JavaScript escape() Function  It is a global function to Encode a string:

 ((exdays==null) ? "" : "; expires="+exdate.toUTCString());

it is codition on one line separator is : and mean that if exdays null will write “” and if not will write ; expires = and exdate +356.

 c_value.indexOf(";", c_start);  mean that indexOf will return the position of “;” start to search from c_start position. For example
var xx=”hello Yasser of Egypt”;
xx.indexOf(“e”,3);
that is mean indexOf will start to search about “e” from character number 3.

JavaScript Libraries

JavaScript libraries - jQuery, Prototype, MooTools.

JavaScript Frameworks (Libraries)

Advanced JavaScript programming (especially the complex handling of browser differences), can often be very difficult and time-consuming to work with.
To deal with these difficulties, a lot of JavaScript (helper) libraries have been developed.
These JavaScript libraries are often called JavaScript frameworks.
In this tutorial, we will take a look at some of the most popular JavaScript frameworks:
  • jQuery
  • Prototype
  • MooTools
All of these frameworks have functions for common JavaScript tasks like animations, DOM manipulation, and Ajax handling. In this tutorial we will teach you how start using them, to make JavaScript programming easier and safer

jQuery: jQuery is the most popular JavaScript framework on the Internet today.

It uses CSS selectors to access and manipulate HTML elements (DOM Objects) on a web page.
jQuery also provides a companion UI (user interface) framework and numerous other plug-ins.
Many of the largest companies on the Web use jQuery:
  • Google – Microsoft – IBM - Netflix

Prototype

Prototype is a JavaScript library that provides a simple API to perform common web tasks.
API is short for Application Programming Interface. It is a library of properties and methods for manipulating the HTML DOM.
Prototype enhances JavaScript by providing classes and inheritance.

MooTools

MooTools is also a framework that offers an API to make common JavaScript programming easier.
MooTools also includes some lightweight effects and animation functions.

Other Frameworks

Here are some other frameworks not covered in this short overview:
YUI - The Yahoo! User Interface Framework is a large library that covers a lot of functions, from simple JavaScript utilities to complete internet widgets.
Ext JS - Customizable widgets for building rich Internet applications.
Dojo - A toolkit designed around packages for DOM manipulation, events, widgets, and more.
script.aculo.us - Open-source JavaScript framework for visual effects and interface behaviors.
UIZE - Widgets, AJAX, DOM, templates, and more.

CDN - Content Delivery Networks

You always want your web pages to be as fast as possible. You want to keep the size of your pages as small as possible, and you want the browser to cache as much as possible.
If many different web sites use the same JavaScript framework, it makes sense to host the framework library in a common location for every web page to share.
A CDN (Content Delivery Network) solves this. A CDN is a network of servers containing shared code libraries.

Google provides a free CDN for a number of JavaScript libraries, including:
  • jQuery -  Prototype – MooTools – Dojo - Yahoo! YUI
To use a JavaScript framework library in your web pages, just include the library in a <script> tag:

Including jQuery

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

Using Frameworks

Before you decide to use a JavaScript framework for your web pages, it might be a good idea to test the framework first.
JavaScript frameworks are very easy to test. You don't have to install them on your computer, and there are no setup programs.
Normally you just have to reference a library file from your web page. 
JavaScript - Testing jQuery
Including jQuery

To test a JavaScript library, you need to include it in your web page.

To include a library, use the <script> tag with the src attribute set to the URL of the library:
Including jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
</body>
</html>
jQuery Described

The main jQuery function is the $() function (the jQuery function). If you pass DOM objects to this function, it returns jQuery objects, with jQuery functionality added to them.

jQuery allows you to select elements by CSS selectors.

In JavaScript, you can assign a function to handle the window's load event:
The JavaScript Way:

function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello jQuery";
}
onload=myFunction;

The jQuery equivalent is different:
The jQuery Way:

function myFunction()
{
$("#h01").html("Hello jQuery");
}
$(document).ready(myFunction);

The last line of the code above, passes the HTML DOM document object to jQuery: $(document).

When you pass DOM objects to jQuery, jQuery returns new jQuery objects wrapped around the HTML DOM objects.

The jQuery function returns a new jQuery object, where ready() is a method.

Since functions are variables in JavaScript, myFunction can be passed as a variable to the jQuery ready method.
Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
function myFunction()
{
$("#h01").attr("style","color:red").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>

As you can see from the example above, jQuery allows chaining.

Chaining is a handy way to perform multiple tasks on one object.
JavaScript - Testing Prototype
Including Prototype

To include a library, use the <script> tag with the src attribute set to the URL of the library:
Including Prototype

<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/
prototype/1.7.1.0/prototype.js>
</script>
</head>
<body>
</body>
</html>
Prototype Described

Prototype provides functions to make HTML DOM programming easier.

Like jQuery, Prototype has its $() function.

The $() function accepts HTML DOM element id values (or DOM elements), and adds new functionality to DOM objects.

Unlike jQuery, Prototype has no ready() method to take the place of window.onload(). Instead, Prototype adds extensions to the browser and the HTML DOM.
The Prototype Way:

function myFunction()
{
$("h01").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);

Event.observe() accepts three arguments:

    The HTML DOM or BOM (Browser Object Model) object you want to handle
    The event you want to handle
    The function you want to call

<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/
prototype/1.7.1.0/prototype.js">
</script>
<script>
function myFunction()
{
$("h01").writeAttribute("style","color:red").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>

As you can see from the example above, like jQuery, Prototype allows chaining.

Chaining is a handy way to perform multiple tasks on one object.
JavaScript Global Properties

Property
   

Description

Infinity
   

A numeric value that represents positive/negative infinity

NaN
   

"Not-a-Number" value

undefined
   

Indicates that a variable has not been assigned a value
JavaScript Global Functions

Function
   

Description

decodeURI()
   

Decodes a URI

decodeURIComponent()
   

Decodes a URI component

encodeURI()
   

Encodes a URI

encodeURIComponent()
   

Encodes a URI component

escape()
   

Deprecated in version 1.5. Use encodeURI() or encodeURIComponent() instead

eval()
   

Evaluates a string and executes it as if it was script code

isFinite()
   

Determines whether a value is a finite, legal number

isNaN()
   

Determines whether a value is an illegal number

Number()
   

Converts an object's value to a number

parseFloat()
   

Parses a string and returns a floating point number

parseInt()
   

Parses a string and returns an integer

String()
   

Converts an object's value to a string

unescape()
   

Deprecated in version 1.5. Use decodeURI() or decodeURIComponent() instead
Decode a URI after encoding it:



<body>

<p id="demo">Click the button to decode a URI after encoding it.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

{

var uri = "my test.asp?name=ståle&car=saab";

var enc = "Encoded URI: " + encodeURI(uri);

var dec = "Decoded URI: " + decodeURI(uri);

var res = enc + "<br>" + dec;

document.getElementById("demo").innerHTML=res;

}

</script>

</body>

2 comments:

  1. David Walsh is Mozilla’s senior web developer, and the core developer for the MooTools
    Javascript Framework. David’s blog reflects his skills in HTML/5, JS and CSS, and offers a ton
    of engaging advice and insight into front-end technologies. Even more obvious is his passion
    for open source contribution and trial-and-error development, making his blog one of the
    most honest and engaging around.
    Website: davidwalsh.name

    ReplyDelete
  2. David Walsh is Mozilla’s senior web developer, and the core developer for the MooTools Javascript Framework. David’s blog reflects his skills in HTML/5, JS and CSS, and offers a ton of engaging advice and insight into front-end technologies. Even more obvious is his passion for open source contribution and trial-and-error development, making his blog one of the most honest and engaging around.
    Website: davidwalsh.name

    ReplyDelete