0% found this document useful (0 votes)
89 views18 pages

Web Design Programming Chapter 3

This document summarizes Chapter 3 of a book on web design programming, covering CSS and JavaScript. It introduces CSS syntax and how to select elements using CSS. It describes the different ways to insert CSS using external, internal, and inline styles. It then covers the cascading order of multiple styles and introduces common things JavaScript can do, such as changing HTML content, attributes, styles, hiding and showing elements.

Uploaded by

Hiziki Tare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
89 views18 pages

Web Design Programming Chapter 3

This document summarizes Chapter 3 of a book on web design programming, covering CSS and JavaScript. It introduces CSS syntax and how to select elements using CSS. It describes the different ways to insert CSS using external, internal, and inline styles. It then covers the cascading order of multiple styles and introduces common things JavaScript can do, such as changing HTML content, attributes, styles, hiding and showing elements.

Uploaded by

Hiziki Tare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 18

WEB DESIGN PROGRAMMING: CHAPTER 3

(CSS AND JavaScript) ----JITENDRA SINGH

3.1 INTRODUCTION TO CSS


 CSS stands for Cascading Style Sheets
 CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
 CSS saves a lot of work. It can control the layout of multiple web pages all at once
 External stylesheets are stored in CSS files

3.2 CSS SYNTAX


A CSS rule-set consists of a selector and a declaration block:

The selector points to the HTML element you want to style.

The declaration block contains one or more declarations separated by semicolons.

Each declaration includes a CSS property name and a value, separated by a colon.

A CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly
braces.

In the following example all <p> elements will be center-aligned, with a red text color:

Example

p {
    color: red;
    text-align: center;
}

3.3 CSS SELECTORS

The element Selector


The element selector selects elements based on the element name.
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

You can select all <p> elements on a page like this (in this case, all <p> elements will be
center-aligned, with a red text color):

Example
p {
    text-align: center;
    color: red;
}

The id Selector
The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element should be unique within a page, so the id selector is used to select one
unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of the
element.

The style rule below will be applied to the HTML element with id="para1":

Example
#para1 {
    text-align: center;
    color: red;
}

Note: An id name cannot start with a number!

The class Selector


The class selector selects elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the name
of the class.

In the example below, all HTML elements with class="center" will be red and center-aligned:

Example
.center {
    text-align: center;
    color: red;
}
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Grouping Selectors
If you have elements with the same style definitions, like this:

h1 {
    text-align: center;
    color: red;
}

h2 {
    text-align: center;
    color: red;
}

p {
    text-align: center;
    color: red;
}

It will be better to group the selectors, to minimize the code.

To group selectors, separate each selector with a comma.

In the example below we have grouped the selectors from the code above:

Example
h1, h2, p {
    text-align: center;
    color: red;

3.4 WAYS TO INSERT CSS


There are three ways of inserting a style sheet:

 External style sheet


 Internal style sheet
 Inline style

External Style Sheet


With an external style sheet, you can change the look of an entire website by
changing just one file!
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Each page must include a reference to the external style sheet file inside the
<link> element. The <link> element goes inside the <head> section:

Example
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

An external style sheet can be written in any text editor. The file should not
contain any html tags. The style sheet file must be saved with a .css extension.

Here is how the "mystyle.css" looks:

body {
    background-color: lightblue;
}

h1 {
    color: navy;
    margin-left: 20px;
}

Internal Style Sheet


An internal style sheet may be used if one single page has a unique style.

Internal styles are defined within the <style> element, inside the <head>
section of an HTML page:

Example
<head>
<style>
body {
    background-color: linen;
}

h1 {
    color: maroon;
    margin-left: 40px;

</style>
</head>
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Inline Styles
An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style
attribute can contain any CSS property.

The example below shows how to change the color and the left margin of a
<h1> element:

Example
<h1 style="color:blue;margin-left:30px;">This is a heading</h1>

3.5 CASCADING ORDER


What style will be used when there is more than one style specified for an HTML
element?

Generally speaking we can say that all the styles will "cascade" into a new
"virtual" style sheet by the following rules, where number one has the highest
priority:

1. Inline style (inside an HTML element)


2. External and internal style sheets (in the head section)
3. Browser default

So, an inline style (inside a specific HTML element) has the highest priority,
which means that it will override a style defined inside the <head> tag, or in an
external style sheet, or a browser default value.
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

3.6 INTRODUCTION <body>


TO JAVASCRIPT <h2>What Can JavaScript Do?</h2>
JavaScript is one of the 3 languages all web
developers must learn: <p>JavaScript can change HTML
   1. HTML to define the content of web attributes.</p>
pages
   2. CSS to specify the layout of web pages <p>In this case JavaScript changes the src
   3. JavaScript to program the behavior of (source) attribute of an image.</p>
web pages
<button
onclick="document.getElementById('myImag
3.7 What can e').src='pic_bulbon.gif'">Turn on the
JAVASCRIPT Do? light</button>

JavaScript Can Change <img id="myImage" src="pic_bulboff.gif"


style="width:100px">
HTML Content
One of many JavaScript HTML methods <button
is getElementById(). onclick="document.getElementById('myImag
This example uses the method to "find" an e').src='pic_bulboff.gif'">Turn off the
HTML element (with id="demo") and changes light</button>
the element content (innerHTML) to "Hello
JavaScript": </body>
<!DOCTYPE html> </html>
<html>
<body>
JavaScript Can Change
<h2>What Can JavaScript Do?</h2>
HTML Styles (CSS)
Changing the style of an HTML element, is a
<p id="demo">JavaScript can change HTML variant of changing an HTML attribute:
content.</p> <!DOCTYPE html>
<html>
<button type="button" <body>
onclick='document.getElementById("demo").i
nnerHTML = "Hello JavaScript!"'>Click Me! <h2>What Can JavaScript Do?</h2>
</button>
<p id="demo">JavaScript can change the style
</body> of an HTML element.</p>
</html>
Note: JavaScript accepts both double and <button type="button"
single quotes: onclick="document.getElementById('demo').s
tyle.fontSize='35px'">Click Me!</button>
JavaScript Can Change </body>
</html>
HTML Attributes JavaScript Can Hide
This example changes an HTML image by
changing the src (source) attribute of an
<img> tag:
HTML Elements
<!DOCTYPE html> Hiding HTML elements can be done by
<html> changing the display style:
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

<!DOCTYPE html>
<html>
Example
<script>
<body>
document.getElementById("demo").innerHTML 
= "My First JavaScript";
<h2>What Can JavaScript Do?</h2> </script>
<p id="demo">JavaScript can hide HTML
elements.</p>
JavaScript in <head> or
<body>
<button type="button" You can place any number of scripts in an
onclick="document.getElementById('demo').s HTML document.
tyle.display='none'">Click Me!</button> Scripts can be placed in the <body>, or in the
<head> section of an HTML page, or in both.
</body> JavaScript in <head>
</html> In this example, a JavaScript function is
JavaScript Can Show placed in the <head> section of an HTML
page.
HTML Elements The function is invoked (called) when a button
is clicked:
Showing hidden HTML elements can also be
done by changing the display style:
<!DOCTYPE html>
Example
<!DOCTYPE html>
<html> <html>
<body>
<head>
<h2>What Can JavaScript Do?</h2>
<script>
function myFunction() {
<p>JavaScript can show hidden HTML
elements.</p>    
document.getElementById("demo").innerH
<p id="demo" style="display:none">Hello TML = "Paragraph changed.";
JavaScript!</p> }
</script>
<button type="button" </head>
onclick="document.getElementById('demo').s <body>
tyle.display='block'">Click Me!</button> <h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
</body> <button type="button" onclick="myFunctio
</html> n()">Try it</button>
</body>
3.8 Where to use </html>
JavaScript?
JavaScript in <body>
The <script> Tag In this example, a JavaScript function is
In HTML, JavaScript code must be inserted placed in the <body> section of an HTML
between <script> and </script> tags. page.
The function is invoked (called) when a button
is clicked:
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Example External JavaScript


<!DOCTYPE html>
<html>
<body> 
Advantages
<h1>A Web Page</h1> Placing scripts in external files has some
<p id="demo">A Paragraph</p> advantages:
<button type="button" onclick="myFunction()"
>Try it</button>  It separates HTML and code
 It makes HTML and JavaScript easier
<script> to read and maintain
function myFunction() {  Cached JavaScript files can speed up
   document.getElementById("demo").innerHT page loads
ML = "Paragraph changed.";
} To add several script files to one page  - use
</script> several script tags:
</body>
</html>
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External JavaScript
Scripts can also be placed in external files:
3.9 JavaScript variables
External file: myScript.js
function myFunction() { JavaScript variables are containers for storing
   document.getElementById("demo").innerHT data values.
ML = "Paragraph changed."; In this example, x, y, and z, are variables:
}
Example
External scripts are practical when the same
code is used in many different web pages. var x = 5;
JavaScript files have the file extension .js. var y = 6;
To use an external script, put the name of the var z = x + y;
script file in the src (source) attribute of a From the example above, you can expect:
<script> tag:  x stores the value 5
 y stores the value 6
Example  z stores the value 11
<!DOCTYPE html>
<html> JavaScript Identifiers
<body> All JavaScript variables must
be identified with unique names.
<script src="myScript.js"></script> These unique names are called identifiers.
Identifiers can be short names (like x and y) or
</body> more descriptive names (age, sum,
</html> totalVolume).
Note: External scripts cannot contain <script> The general rules for constructing names for
tags. variables (unique identifiers) are:
 Names can contain letters, digits,
underscores, and dollar signs.
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

 Names must begin with a letter Then we "output" the value inside an HTML
 Names can also begin with $ and _ paragraph with id="demo":
 Names are case sensitive (y and Y are
different variables) Example
 Reserved words (like JavaScript <p id="demo"></p>
keywords) cannot be used as names
<script>
JavaScript Data Types var carName = "Volvo";
document.getElementById("demo").innerHTML 
= carName; 
JavaScript variables can hold numbers like </script>
100 and text values like "John Doe".
In programming, text values are called text
strings.
One Statement, Many
JavaScript can handle many types of data, but
for now, just think of numbers and strings.
Variables
Strings are written inside double or single
You can declare many variables in one
quotes. Numbers are written without quotes.
statement.
If you put a number in quotes, it will be
Start the statement with var and separate the
treated as a text string.
variables by comma:
var person = "John Doe", carName = "Volvo",
Example price = 200;
var pi = 3.14;
var person = "John Doe";
A declaration can span multiple lines:
var answer = 'Yes I am!';
var person = "John Doe",
carName = "Volvo",
Declaring (Creating) price = 200;

JavaScript Variables 3.10 JavaScript


Creating a variable in JavaScript is called Operators
"declaring" a variable.
You declare a JavaScript variable with JavaScript Arithmetic
the var keyword:
var carName; Operators
Arithmetic operators are used to perform
After the declaration, the variable has no arithmetic on numbers:
value. (Technically it has the value
of undefined)
To assign a value to the variable, use the equal Operato Description
sign: r
carName = "Volvo";

You can also assign a value to the variable + Addition


when you declare it:
var carName = "Volvo";
- Subtraction
In the example below, we create a variable
called carName and assign the value "Volvo"
to it. * Multiplication
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

The + operator can also be used to add


(concatenate) strings.
/ Division
Example
txt1 = "John";
% Modulus txt2 = "Doe";
txt3 = txt1 + " " + txt2;

++ Increment The result of txt3 will be:


John Doe

-- Decrement
Adding Strings and
JavaScript Assignment Numbers
Operators Adding two numbers, will return the sum, but
Assignment operators assign values to adding a number and a string will return a
JavaScript variables. string:

Example
Operator Exampl Same As x = 5 + 5;
e y = "5" + 5;
z = "Hello" + 5;

= x=y x=y
The result of x, y, and z will be:
10
+= x += y x=x+y 55
Hello5
Note: If you add a number and a string, the
-= x -= y x=x–y result will be a string!

JavaScript Comparison
*= x *= y x=x*y
Operators
/= x /= y x=x/y
Operato Description
r
%= x %= y x=x%y

== equal to
The addition assignment operator (+=) adds
a value to a variable.
=== equal value and equal type
JavaScript String
Operators != not equal
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

!= = not equal value or not equal type 3.11 JavaScript


Conditional
> greater than Statements
In JavaScript we have the following
< less than conditional statements:
 Use if to specify a block of code to be
executed, if a specified condition is
>= greater than or equal to true
 Use else to specify a block of code to
be executed, if the same condition is
<= less than or equal to false
 Use else if to specify a new condition
to test, if the first condition is false
? ternary operator  Use switch to specify many alternative
blocks of code to be executed

JavaScript Logical The if Statement


Operators
Use the if statement to specify a block of
JavaScript code to be executed if a condition
Operato Description is true.
r
Syntax
if (condition) {
&& logical and     block of code to be executed if the condition
is true
}
|| logical or
Note that if is in lowercase letters. Uppercase
letters (If or IF) will generate a JavaScript
! logical not error.

Example
JavaScript Type
Operators Make a "Good day" greeting if the hour is less
than 18:00:
if (hour < 18) {
    greeting = "Good day";
Operator Description }

The result of greeting will be:


Typeof Returns the type of a variable Good day

Instanceo Returns true if an object is an The else Statement


f instance of an object type
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Use the else statement to specify a block of     greeting = "Good evening";


code to be executed if the condition is false. }
if (condition) {
    block of code to be executed if the condition The result of greeting will be:
is true Good morning
} else { 
    block of code to be executed if the condition
is false 3.12 Javascript Functions
}
A JavaScript function is a block of code
Example designed to perform a particular task.
A JavaScript function is executed when
If the hour is less than 18, create a "Good day" "something" invokes it (calls it).
greeting, otherwise "Good evening":
if (hour < 18) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
Example
}
function myFunction(p1, p2) {
    return p1 * p2;              // The function returns
The result of greeting will be:
the product of p1 and p2
Good day
}

The else if Statement JavaScript Function


Use the else if statement to specify a new Syntax
condition if the first condition is false. A JavaScript function is defined with
the function keyword, followed by a name,
Syntax followed by parentheses ().
if (condition1) { Function names can contain letters, digits,
    block of code to be executed if condition1 is underscores, and dollar signs (same rules as
true variables).
} else if (condition2) { The parentheses may include parameter names
    block of code to be executed if the condition1 separated by commas:
is false and condition2 is true (parameter1, parameter2, ...)
} else { The code to be executed, by the function, is
    block of code to be executed if the condition1 placed inside curly brackets: {}
is false and condition2 is false function name(parameter1, parameter2,
} parameter3) {
    code to be executed
Example }
Function parameters are listed inside the
If time is less than 10:00, create a "Good parentheses () in the function definition.
morning" greeting, if not, but time is less than Function arguments are the values received
20:00, create a "Good day" greeting, otherwise by the function when it is invoked.
a "Good evening": Inside the function, the arguments (the
if (time < 10) { parameters) behave as local variables.
    greeting = "Good morning"; A Function is much the same as a Procedure
} else if (time < 20) { or a Subroutine, in other programming
    greeting = "Good day"; languages.
} else {
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

3.13 Javascript Arrays Example


var cars
JavaScript arrays are used to store multiple = new Array("Saab", "Volvo", "BMW");
values in a single variable.

Example
Access the Elements of
an Array
var cars = ["Saab", "Volvo", "BMW"];
You refer to an array element by referring to
What is an Array? the index number.
This statement accesses the value of the first
An array is a special variable, which can hold element in cars:
more than one value at a time. var name = cars[0];
If you have a list of items (a list of car names,
for example), storing the cars in single This statement modifies the first element in
variables could look like this: cars:
var car1 = "Saab"; cars[0] = "Opel";
var car2 = "Volvo";
var car3 = "BMW"; Example
var cars = ["Saab", "Volvo", "BMW"];
However, what if you want to loop through document.getElementById("demo").innerHTML 
the cars and find a specific one? And what if = cars[0];
you had not 3 cars, but 300?
The solution is an array! Access the Full Array
An array can hold many values under a single
name, and you can access the values by With JavaScript, the full array can be accessed
referring to an index number. by referring to the array name:

Example
var cars = ["Saab", "Volvo", "BMW"];
Creating an Array document.getElementById("demo").innerHTML 
= cars;
Using an array literal is the easiest way to
create a JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];        3.14 JavaScript Loops
Example Loops are handy, if you want to run the same
var cars = ["Saab", "Volvo", "BMW"]; code over and over again, each time with a
different value.
Often this is the case when working with
Using the JavaScript arrays:

Keyword new Instead of writing:


text += cars[0] + "<br>"; 
text += cars[1] + "<br>"; 
The following example also creates an Array, text += cars[2] + "<br>"; 
and assigns values to it: text += cars[3] + "<br>"; 
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

text += cars[4] + "<br>";  The JavaScript for/in statement loops through


text += cars[5] + "<br>"; the properties of an object:

Example
var person = {fname:"John", lname:"Doe",
You can write: age:25}; 
for (i = 0; i < cars.length; i++) { 
    text += cars[i] + "<br>"; var text = "";
} var x;
for (x in person) {
Different Kinds of     text += person[x];
}
Loops
The While Loop
JavaScript supports different kinds of loops:
The while loop loops through a block of code
 for - loops through a block of code a as long as a specified condition is true.
number of times
 for/in - loops through the properties of Syntax
an object while (condition) {
 while - loops through a block of code     code block to be executed
while a specified condition is true }
 do/while - also loops through a block
of code while a specified condition is Example
true
In the following example, the code in the loop
will run, over and over again, as long as a
The For Loop variable (i) is less than 10:

Example
The for loop is often the tool you will use while (i < 10) {
when you want to create a loop.     text += "The number is " + i;
The for loop has the following syntax:     i++;
for (statement 1; statement 2; statement 3) { }
    code block to be executed
}
The Do/While Loop
Statement 1 is executed before the loop (the
code block) starts. The do/while loop is a variant of the while
Statement 2 defines the condition for running loop. This loop will execute the code block
the loop (the code block). once, before checking if the condition is true,
Statement 3 is executed each time after the then it will repeat the loop as long as the
loop (the code block) has been executed. condition is true.

Example Syntax
for (i = 0; i < 5; i++) { do {
    text += "The number is " + i + "<br>";     code block to be executed
} }
while (condition);
The For/In Loop
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Example
lastName Doe
The example below uses a do/while loop. The
loop will always be executed at least once,
even if the condition is false, because the code age 50
block is executed before the condition is
tested:
eyeColor blue
Example
do {
    text += "The number is " + i;
    i++;
} Object Methods
while (i < 10);
3.15 JavaScript Objects Methods are actions that can be performed on
objects.
Methods are stored in properties as function
definitions.
JavaScript variables are containers for data
values.
This code assigns a simple value (Fiat) to Property Property Value
a variable named car:
var car = "Fiat";
Objects are variables too. But objects can firstNam John
contain many values. e
This code assigns many values (Fiat, 500,
white) to a variable named car:
var car = {type:"Fiat", model:"500", lastName Doe
color:"white"};
The values are written as name:value pairs
(name and value separated by a colon). age 50
Note: JavaScript objects are containers
for named values
eyeColor blue
Object Properties
fullName function() {return this.firstName
The name:values pairs (in JavaScript objects) + " " + this.lastName;}
are called properties.
var person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"}; JavaScript objects are containers for named
values called properties or methods.

Property Property Value


Object Definition
firstNam John
e You define (and create) a JavaScript object
with an object literal:
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Example Example
var person = {firstName:"John", <!DOCTYPE html>
lastName:"Doe", age:50, eyeColor:"blue"}; <html>
<body>
Accessing Object <p>Creating and using an object method.</p>
Properties <p>An object method is a function definition,
stored as a property value.</p>
You can access object properties in two ways:
objectName.propertyName <p id="demo"></p>

or <script>
objectName["propertyName"] var person = {
firstName: "John",
Example1 lastName : "Doe",
id : 5566,
<!DOCTYPE html> fullName : function() {
<html> return this.firstName + " " + this.lastName;
<body> }
};
<p>
There are two different ways to access an object document.getElementById("demo").innerHTML
property: = person.fullName();
</p> </script>
<p>You can use person.property or </body>
person["property"].</p> </html>
<p id="demo"></p> 3.16 JavaScript Cookies
Cookies are small items of data, each consisting
<script> of a name and a value, stored on behalf of a
var person = { website by visitors’ web browsers. In JavaScript,
firstName: "John", cookies can be accessed through
lastName : "Doe", the document.cookie object, but the interface
id : 5566 provided by this object is very primitive.
}; Cookies.js is a JavaScript object that allows
document.getElementById("demo").innerHTML cookies to be created, retrieved, and deleted
= through a simple and intuitive interface.
person.firstName + " " + person.lastName;
</script> Download Cookies.js
Download one of the files below and either
incorporate it into your code or serve it as a separate
</body>
file.
</html>
File Size Description

Accessing Object Cookies.js


Cookies.src.j
661 bytes Minified version
3,957 Full version, with

Methods s bytes comments


The code creates a global object, Cookies, which has
functions to create, retrieve, and delete cookies.
You access an object method with the
following syntax:
Creating cookies
objectName.methodName()
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

Cookies can be created using the set function, The domain property allows an alternative


which takes the cookie name and value as domain to be specified:
parameters: 1 // create a cookie that is accessible on all
1 // create a cookie 2 subdomains of example.com
2 Cookies.set('theme', Cookies.set('theme', 'green', {domain :
'green'); '.example.com'});
A cookie set in this way will be deleted when Finally, the secure property can be set to true to
the visitor closes their web browser, will only be instruct the browser to send the cookie only over
accessible within the current directory on the encrypted connections:
current domain name, and will be sent over both 1 // create a cookie that is sent only over
encrypted and unencrypted connections. These 2 encrypted connections
features can be controlled through an optional Cookies.set('theme', 'green', {secure :
third parameter, which is an object with four true});
possible properties.
The expiry property allows the cookie can be Retrieving cookies
given an expiry date. Cookies with an expiry The value of a cookie can be retrieved using
date will persist between browsing sessions, and the get function, which takes the cookie name as
only be deleted when the expiry date is reached a parameter:
or the visitor instructs the browser to do so. The 1 // retrieve the value of the theme
value of the property can be either a date on 2 cookie
which the cookie will expire or a number of var theme = Cookies.get('theme');
seconds after which the cookie should expire: If there is no cookie with the specified name, the
1 // create a cookie that expires after one value undefined is returned. There may be more
2 hour than one cookie with the same name if they were
3 Cookies.set('theme', 'green', {expiry : set for different paths or subdomains. In this
4 3600}); case the get function returns the most specific
5 cookie (the one set for the longest path).
// create a cookie that expires on 1st Passing true as a second parameter to
January 2030
the get function will cause it to return an array
Cookies.set('name', 'Stephen Morley',
containing the values of all cookies with the
{expiry : new Date(2030, 0, 1)});
specified name, in order of specificity:
Every cookie is accessible only within a
1 // retrieve the values of any theme
particular path, which defaults to the current
2 cookies
directory — for example, a cookie set on a page
var themes = Cookies.get('theme', true);
at http://example.com/news/ would by default be
accessible from
http://example.com/news/archives/ but not from
Deleting cookies
A cookie can be deleted using
the home page of the site. The path property
the clear function, which takes the cookie name
allows an alternative path to be specified:
as a parameter:
1 // create a cookie that is accessible
1 // delete the theme
2 anywhere on the site
2 cookie
3 Cookies.set('theme', 'green', {path : '/'});
Cookies.clear('theme');
4
If the cookie was set for a path or domain other
5 // create a cookie that is accessible only
than the current path and domain, these must be
within the news directory
passed to the clearfunction through its optional
Cookies.set('country', 'uk', {path :
'/news/'}); second parameter:
Every cookie is accessible only on a particular 1 // delete the site-wide theme
domain, which defaults to the current domain 2 cookie
and its subdomains — for example, a cookie set 3 Cookies.clear(
on news.example.com would by default be 4 'theme',
accessible from archives.news.example.com but 5 {
not from the main domain example.com. 6 path : '/',
WEB DESIGN PROGRAMMING: CHAPTER 3
(CSS AND JavaScript) ----JITENDRA SINGH

7 domain : '.example.com'
});

You might also like