HTML
HTML
What is HTML?
• HTML(Hyper Text Markup Language)
is a language for describing web pages.
not a programming language
uses markup tags to describe web pages.
• Most Web documents are created using HTML.
Documents are saved with extension .html or .htm.
• Markup?
Markup Tags are strings in the language surrounded by a < and a > sign.
Opening tag: <html> Ending tag: </html>
Not case sensitive.
Can have attributes which provide additional information about HTML elements on
your page. Example
o <body bgcolor="red">
o <table border="0">
3
HTML
• An HTML document appears as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>
HTML Head Section: contain information about the document. The browser does not
display this information to the user. Following tags can be in the head section:
<base>, <link>, <meta>, <script>, <style>, and <title>.
HTML Body Section: defines the document’s body. Contains all the contents of the
document (like text, images, colors, graphics, etc.).
4
<HTML>
<HEAD>
<TITLE>Body Tag</TITLE>
</HEAD>
<BODY BGCOLOR="pink" text="red"
alink="green" link="yellow">
<a href="body.html">background</a>
color of the page is pink. and text color is red
</BODY>
</HTML>
5
<html>
<body>
<b>This is in bold font</b>
<i>This text is in Italics</i>
<u>This text is Underlined</u>
<small>This is small text.</small>
<font size=7>This text is very large</font>
<font color=”Blue”>This is Blue Text.</font>
<strike>This is strikethrough style text</strike>
The chemical formula of water is h<sub>2</sub>o.
A simple formula for a parabola is y = x<sup>2</sup>.
</body>
</html>
6
<html>
<head><title>This is the first html page</title>
<body>This is the first html page created
<h1 align=”left”>This is level 1 heading</h1>
<h2 align=”right”>This is level 2 heading</h2>
<h3 align=”center”>This is level 3 heading</h3>
</body>
</head>
</html>
8
<body> <p>
This paragraph contains a lot of lines
in the source code,
but the browser ignores it. </p>
<hr size="2" width="50%" color="blue“ align = “left” > <p>
Notice the horizontal rule occupying 50 % of the window width.
</p> This paragraph contains <br> line breaks in the
source code <br> so this is the third line displayed within the paragraph.
</body>
9
• Select the type of numbering system with the type attribute. Example:
o A-Uppercase letters. <OL TYPE=A>
o a-Lowercase letters. <OL TYPE=a>
o I-Uppercase Roman letters
o i-Lowercase Roman letters
o 1-Standard numbers, default
10
• To change the type of bullet used throughout the list, place the TYPE attribute
in the <UL> tag at the beginning of the list.
DISC (default) gives bullet in disc form.
SQUARE gives bullet in square form.
CIRCLE gives bullet in circle form.
<ul>
<li type=‘disc’>Latte</li>
<li type=‘square’>Expresso</li>
<li type=‘circle’>Mocha</li>
</ul>
11
Adding Image
• Images are added into a document using <img> tag.
• Attributes of <img> tag are:
alt: Alternative text to display for non-graphical browsers.
align: Image horizontal alignment. Valid values: left, right, center.
width/Height: Sets the width and height of the image.
src: Specifies the image path or source.
Table
• Use <table> tag to create a table.
• Table Attributes:
Border: <table border=“2”>………</table>
Align: defines the horizontal alignment of the table element.
o Values of the align attribute are right, left and center. <table align=“center”>
Width: defines the width of the table element.
o <table width=“75%”>………</table>
o <table width=“400”>………</table>
• Example:
<table border="1">
<tr border="1">
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
13
Table Data
• You can insert a bgcolor attribute in a <table>, <td>, <th> or <tr> tag to set the
color of the particular element.
<table bgcolor="cyan">
<tr bgcolor="blue">
<table bgcolor="cyan">
<tr bgcolor="blue">
<th bgcolor="red">Header 1</th> <th>Header 2</th>
</tr>
<tr> <td bgcolor="green">data 1</td> <td>data 2</td> </tr>
</table>
14
<ul>
<li><a href=home.html>mumbai</a></li>
<li><a href=home.html>pune</a></li>
<li><a href=home.html>nasik</a></li>
</ul>
<table border=1>
<tr><th>team<th>points<th>grade</tr>
<tr><td><a href=home.html>mumbai</a></td><td>90</td><td>a</td></tr>
<tr><td><a href=home.html>pune</a></td><td>86</td><td>b</td></tr>
<tr><td><a href=home.html>nasik</a></td><td>80</td><td>c</td></tr>
</table>
15
Text Field
• Single Line Text Fields: used to type letters, numbers, etc. in a form.
<INPUT TYPE=”type” NAME=”name” SIZE=”number” VALUE=”value” maxlength=n>
Eg:
<form>
First name: <input type="text" name="firstname“ value=“fname>
Last name:<input type="text" name="lname">
</form>
Check Box
• Lets you select one or more options from a limited number of choices.
<input type=“checkbox” name=“name” value=“value” [checked] [disabled]> Checkbox
Label
Content of value attribute is sent to the form's action URL.
Radio Buttons
<input type=“radio” name=“name” value=“value” [checked] [disabled]> Radio Button Label
• Content of the value attribute is sent to the form's action URL.
<form>
<input type="radio" name="sex" value="male"/>Male<br>
<input type="radio" name="sex" value="female"/> Female
</form>
Hidden Field
• Allows to pass information between forms:
• <input type=“hidden” name=“name” size=“n” value=“value”/>
• <input type=“hidden” name=“valid_user” size=“5” value=“yes”/>
18
Password Fields
• <input type=“password” name=“name” size=n value=“value” [disabled]>
Eg: Enter the password:<input type=“password” name=“passwd” size=20 value=“abc”>
<FORM>
Please select file that you want to upload:
<INPUT name=“file” type=“file”> <BR>
<INPUT type=“submit” >
</FORM>
Action Buttons
• To add a button to a form use:
• <input type=“button” name=“btnCalculate” value=“Calculate”/>
• To submit the contents of the form use:
• <input type=“submit” name=“btnSubmit” value=“Submit”/>
• To reset the field contents use:
• <input type=“reset” name=“btnReset” value=“Reset”/>
19
Drop-Down List
<select name=“name” multiple=“true/false” size=n [disabled]>
<option [selected] [disabled] [value]>Option 1</option>…
</select>
Multiple: States if multiple element selection is allowed.
Size: Number of visible elements.
Disabled: States if the option is to be disabled after it first loads.
Eg:
<form>
<select multiple size="3" name="pref">
<option value="ih" selected>Internet-HTML</option>
<option value="js">Javascript</option>
<option value="vbs">VBscript</option>
<option value="as">ASP</option>
<option value="xm">XML</option>
<option value="jv">JAVA</option>
<option value="jsp">jsp</option>
</select>
</form>
<html><head><title>form examples</title></head>
<body bgcolor="pink">
<form name="form1" action="store.html" method="post">
Complete example
<p>
<strong>Enter first name</strong>: <input name="username">
<strong>Enter lastname</strong>: <input maxlength="30" name="surname"></p>
<p><strong>Enter address:</strong>
<textarea name="addr" rows="3" readonly value="sjdshd"></textarea>
<br><br>
<strong>Select the training programs attended:</strong>
<input type="checkbox" value="internet/html" name="internet-html"> Internet/HTML
<input type="checkbox" checked value="c programming" name="c-programming">C Programming
<input type="checkbox" value="dbms-sql" name="dbms-sql"> DBMS-SQL </p>
<p><strong>Select the stream you belong to:</strong>
<input type="radio" value="science" name="s-grp"> Science
<input type="radio" value="arts" name="s-grp"> Arts
<input type="radio" value="commerce" name="s-grp"> Commerce
<input type="radio" value="oth2" name="s-grp">Engineering </p>
<strong>Which training program would you like to attend ?</strong>
<select size="5" multiple name="pref">
<option value="ih" selected>Internet-HTML
<option value="js">Javascript
<option value="vbs">VBscript
<option value="as">ASP
<option value="xm">XML
<option value="jv">JAVA
<option value="jsp">jsp</option>
</select> <br>
<input type="button" value="exit" name="but">
<input type="submit" value="save">
<input type="reset" value="reset">
</form></body></html>
HTML5
What's new in HTML5?
• Required - A "Required Field" is a field that must be filled in with value before
submission of a form
• <input name="name" type="text" required />
New Form elements
• Email - This field is used to check whether the string entered by the user is valid
email id or not.
<input id="email" name="email" type="email" />
• Search - used for search fields (behaves like a regular text field).
<input id="mysearch" type="search" />
• Tel - used for input fields that should contain a telephone number.
<input type="tel" name="usrtel">
• url - is used for input fields that should contain a URL address.
Depending on browser support, the url field can be automatically validated when
submitted.
• color – displays a color palette
New Form elements
• Number - used for input fields that should contain a numeric value.
Min and max parameters provided to limit the values.
Browser will treat it as simple textfield if it doesn’t support this type.
<input id="movie" type="number" value="0"/>
<input type="number“ min="0“ max="50“ step="2“ value="6">
• Range - used for input fields that should contain a value within a range
Browser will treat it as simple textfield if it doesn’t support this type
<input id="test" type="range"/>
<input type="range" min="1" max="20" value="0">
New Form elements
<input id="country_name"
name="country_name"
type="text“
list="country" />
<datalist id="country">
<option value="Australia">
<option value="Austria">
<option value="Algeria">
<option value="Andorra">
<option value="Angola">
</datalist>
Audio
• Until now, there has never been a standard for playing audio on a web page.
Today, most audio is played through a audio plugin (like Microsoft Windows Media
player, Microsoft Silverlight ,Apple QuickTime and the famous Adobe Flash).
However, not all browsers have the same plugins.
HTML5 specifies a standard way to include audio, with the audio element; The audio
element can play sound files, or an audio stream.
Currently, there are 3 supported formats for the audio element: Ogg Vorbis, MP3,
.webm and WAV
Other properties like auto play, loop, preload area also available
<audio controls>
<source src="vincent.mp3" type="audio/mpeg"/>
<source src="vincent.ogg" type="audio/ogg"/>
</audio>
Video
• Until now, there hasn't been a standard for showing video on a web page.
Today, most videos are shown through a plugin (like Flash). However, not all
browsers have the same plugins.
HTML5 specifies a standard way to include video with the video element
Supported video formats for the video element : Ogg, MP4, WebM, .flv, .avi
Attributes : width, height, poster, autoplay, controls, loop, src
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
</script>
New Semantic Elements
Fat footer on
the w3c site
33
What is CSS?
• Cascading Styles Sheets - a way to style and present HTML.
HTML deals with content and structure, stylesheet deals with formatting and
presentation of that document.
Allows to control the style and layout of multiple Web pages all at once.
• Example:
Messy HTML
<font color="#FF0000" face="Verdana, Arial, Helvetica, sans-serif">
<strong>This is text</strong></font>
• Why CSS?
saves time
Pages load faster
Easy maintenance
Superior styles to HTML
34
CSS Syntax
• A CSS rule has two parts: a selector, and one or more declarations:
linked_ex2.css
37
body {
background: #00ff00 url("smiley.gif") no-repeat fixed center;
}
<html>
<head><style>
body {
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
margin-right:200px;
}
</style> </head>
<body>
<h1>Hello World!</h1>
<p>Background no-repeat, set position example.</p>
<p>Now the background image is only shown once, and positioned away from the text.</p>
<p>In this example we have also added a margin on the right side, so the background image will never
disturb the text.</p>
</body></html>
CSS Text
• CSS Text Properties
<style>
h1 {text-decoration:overline;}
h2 {text-decoration:line-through;}
h3 {text-decoration:underline;}
</style>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
Demo : <style>
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
</style>
<body>
<p class="uppercase">This is some text.</p>
<p class="lowercase">This is some text.</p>
<p class="capitalize">This is some text.</p>
</body>
<head> <style>
h1 {text-align:center;color:#00ff00;}
p.date {text-align:right;}
p.main {text-align:justify;}
p.ex {color:rgb(0,0,255);}
p.indent {text-indent:50px;}
</style> </head>
<body>
<h1>Hello World!</h1>
<p class="date"> Sep 2013</p>
<p class="main indent">The CSS property text-align corresponds to the attribute align used in old versions of
HTML. Text can either be aligned to the left, to the right or centred. In addition to this, the value justify will
stretch each line so that both the right and left margins are straight. You know this layout from for example
newspapers and magazines. </p>
<p class="ex">The property text-decoration makes it is possible to add different "decorations" or "effects" to
text. </p>
</body>
More examples
• P { word-spacing:30px; }
• p.small {line-height:70%;}
• p.big {line-height:200%;}
• h1 {letter-spacing:2px;}
• h2 {letter-spacing:-3px;}
CSS : Styling Fonts
• CSS font properties define the font family, boldness, size, and the style of a
text.
• Example:
p.normal {font-weight:normal;}
p{font-family:"Times New Roman", Times;}
p.italic {font-style:italic;}
h1 {font-size:40px;}
p.small { font-variant:small-caps; }
Styling lists
• The CSS list properties allow you to: Example:
Set different list item markers for ordered lists ul.circle {list-style-type:circle}
ol.upper-roman {list-style-type:upper-roman}
Set different list item markers for unordered lists ul { list-style-image: url('sqpurple.gif'); }
Set an image as the list item marker
• CSS List Properties
list-style-image Specifies an image as the list-item marker
list-style-position Should the list-item markers appear inside or outside the content flow
list-style-type Specifies the type of list-item marker
<html>
<head>
<style> Image and table
ul { list-style-image:url('sqpurple.gif’); }
</style> img {
</head> float: right;
<body> margin: 0 0 10px 10px;
<ul> }
<li>Coffee</li>
<li>Tea</li> table{
<li>Coca Cola</li> border: 1px solid black;
</ul> border-collapse: collapse;
</body> }
CSS Box Model
• The CSS box model is essentially a box that wraps around HTML elements; it
consists of:
Margin - Clears an area around the border. The margin does not have a background color,
it is completely transparent
Border - A border that goes around the padding and content. The border is affected by the
background color of the box
Padding - Clears an area around the content; padding is affected by the background color
of the box
Content - The content of the box, where text and images appear
• Padding defines the inner distance of elements to the end of the box.
• Example
padding-top:25px; <head><style>
padding-bottom:25px; p { background-color:yellow; }
padding-right:50px; p.padding {
padding-left:50px; padding:25px 25px 50px 50px;
}
</style></head>
<body>
<p>This is a paragraph with no specified padding.</p>
<p class="padding">This is a paragraph with specified paddings.</p>
</body>
Margins
• Margins allow you to put a bigger distance between your elements
the margin is an outer, invisible border around your element.
<style type="text/css">
You can define the margins for a
.box {
box individually or combine them
background-color: DarkSeaGreen;
into one statement.
width: 100px;
height: 100px;
.box { ….; margin: 10px 10px 10px 10px; }
margin-top: 10px;
margin-right: 5px;
margin-bottom: 10px;
margin-left: 5px;
}
</style>
<div class="box"> Box </div>
<head>
<style>
p.ex1 {margin:2cm 4cm 3cm 4cm}
</style>
</head>
<body>
<p>A paragraph with no specified margins.</p>
<p class="ex1">A paragraph with specified margins.</p>
<p>A paragraph with no specified margins.</p>
</body>
CSS Border
• The border property is a shorthand for the following individual border
properties: border-width, border-style (required), border-color
<style type="text/css">
.box {
width: 100px;
height: 100px;
border-color: Blue;
border-width: 2px;
border-style: solid;
} p { border: 5px solid red; }
</style>
<div class="box">
Hello, world!
</div>
<style> #rcorners3 {
#rcorners1 { border-radius: 25px;
border-radius: 25px; background: url(paper.gif);
background: #8AC007; background-position: left top;
padding: 20px; background-repeat: repeat;
width: 100px; padding: 20px;
height: 100px; width: 100px;
} height: 100px;
#rcorners2 { }
border-radius: 25px; </style>
border: 2px solid #8AC007; <p id="rcorners1">Rounded corners!</p>
padding: 20px; <p id="rcorners2">Rounded corners!</p>
width: 100px; <p id="rcorners3">Rounded corners!</p>
height: 100px;
}
<style>
.c1{text-shadow: 2px 2px;}
.c2{text-shadow: 2px 2px red;}
.c3{text-shadow: 2px 2px 5px red;}
.c4{color: white; text-shadow: 2px 2px 4px #000000;}
</style>
<p class="c1">para-1</p>
<p class="c2">para-2</p>
<p class="c3">para-3</p>
<style>
<p class="c4">para-4</p>
.c1{box-shadow: 10px 10px;}
.c2{box-shadow: 10px 10px grey;}
.c3{ box-shadow: 10px 10px 5px grey;}
p { width: 300px; height: 100px; padding: 15px; background-color:
yellow; }
</style>
<p class="c1">para-1</p>
<p class="c2">para-2</p>
<p class="c3">para-3</p>
Javascript
Overview
• JavaScript is Netscape's cross-platform, object-based scripting language
JavaScript code is embedded into HTML pages
It is a lightweight programming language
Client-side JavaScript extends the core language by supplying objects to control a
browser and its Document Object Model
• Why use Javascript?
Provides HTML designers a programming tool :
Puts dynamic text into an HTML page
Reacts to events
Reads and writes to HTML elements :
Can be used to perform Client side validation
<html>
The <SCRIPT> tag <head> </head>
<body>
<SCRIPT> <script type="text/javascript">
JavaScript statements … document.write("<H1>Hello World!</H1>");
</SCRIPT> alert(“some message”);
console.log(“some message”);
</script>
</body></html>
Embedding JavaScript in HTML
<html>
• Where to Write JavaScript?
<head>
Head Section <script type="text/javascript">
Body Section function message() {
alert(“Hello World")
External File }
</script>
<html> </head>
<head></head> <body onload="message()">
<body > </body>
<script language=“javascript"> </html>
document.write(“Hello World!“)
</script>
</body>
</html>
<head>
<script src="common.js">
<!– no javascript statements //common.js file contents
</ script> var msg
</head> msg=“<h1>in external file</h1>"
<body>
<script>
document.write("display value of a variable”+msg)
</script>
</body>
Data Types in JavaScript
• JavaScript is a free-form language. Need not declare all variables, classes,
and methods
• Variables in JavaScript can be of type:
Number (4.156, 39)
String (“This is JavaScript”)
Boolean (true or false)
Null (null) usually used to indicate the absence of a value
• Variables that exist only inside a function are called Local variables
• Variables that exist throughout the script are called Global variables
Their values can be changed anytime in the code and even by other functions
Predefined Functions
• isFinite: evaluates an argument to determine if it is a finite number.
isNaN(0) //false
• Parseint and parsefloat isNaN('123') //false
isNaN('Hello') //true
Returns a numeric value for string argument.
parseInt (str)
parseFloat (str)
parseInt() interprets any
parseInt("3 blind mice") // => 3 number beginning with “0x” or
parseFloat(" 3.14 meters") // => 3.14 “0X” as hexadecimal no
parseInt("-12.34") // => -12
parseInt("0xFF") // => 255
parseInt("0xff") // => 255
parseInt("-0XFF") // => -255
parseFloat(".1") // => 0.1
parseInt("0.1") // => 0
2.4: JavaScript Functions
parseInt(".1") // => NaN: integers can't start with "."
parseFloat("$72.47"); // => NaN: numbers can't start with "$"
Predefined Core Objects
Lesson 10. Cascading Style Sheets
65
String Objects
• Creating a string object:
var myString = new String(“characters”)
var myString = “fred”
String functions
• indexOf () : returns the position of the first occurrence of a specified string
value in a string.
index values start their count with 0.
If no match occurs within the main string, the returned value is -1.
string.indexOf( searchString [, startIndex])
• toLowerCase() / toUpperCase()
Eg: var str="Hello World!";
str.toLowerCase() //returns hello world
str.toUpperCase() //returns HELLO WORLD
• slice( startIndex [, endIndex])
Extracts a part of a string and returns the extracted part in a new string
String functions
• split(“delimiterCharacter”[, limitInteger]) - Splits a string into array of strings
string.split(“delimiterCharacter”[, limitInteger])
Output :
var str = "zero one two three four"; zero
var arr = str.split(" ");
one
for(i = 0; i < str.length; i++){ document.write(“<br>” + arr[i]); }
two
var myString = “Anderson,Smith,Johnson,Washington” three
var myArray = myString.split(“,”) four
var itemCount = myArray.length // result: 4
Date
• Date object allows the handling of date and time information.
All dates are in milliseconds from January 1, 1970, 00:00:00.
Dates before 1970 are invalid dates.
• There are different ways to define a new instance of the date object:
var d = new Date() //Current date
var d = new Date(milliseconds)
var d = new Date(dateString)
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds)
<script>
var d=new Date();
document.write(d);
</script>
Array
• An array is data structure for storing and manipulating ordered collections of
data.
• An array can be created in several ways.
Eg1: Regular: ----------------------------------------- var cars=new Array();
Eg 2: Condensed: cars[0]="Spark";
o var cars=new Array("Spark","Volvo","BMW");
cars[1]="Volvo";
cars[2]="BMW";
Eg 3: Literal:
o var cars=["Spark","Volvo","BMW"];
Eg 4: var matrix = [[1,2,3], [4,5,6], [7,8,9]];
Eg 5 : var sparseArray = [1,,,,5];
• Deleting an array element eliminates the index from the list of accessible index
values
delete is a unary operator that attempts to delete myArray.length// result: 5
the object property or array element specified delete myArray[2]
myArray.length// result: 5
This does not reduce array’s length
myArray[2] // result: undefined
71
arrayObject.concat(array2)
var arrayText = myArray.join(“,”)
var a1 = new Array(1,2,3)
var a2 = new Array(“a”,”b”,”c”)
var a3 = a1.concat(a2)
// result: array with values 1,2,3,”a”,”b”,”c”
Example:
obj.methodName = function_name
obj.methodName(params)
• window.open(URL,name,specs)
URL : Specifies the URL of the page to open. If no URL is specified, a new window
with about:blank is opened
Name : Specifies the target attribute or the name of the window.
Specs : comma-separated list of items.
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>"); example opens an
myWindow.focus(); about:blank page in a new
browser window:
77
<SCRIPT>
function valSelected(){
var radio = document.getElementsByClassName("r1");
for(var i = 0; i < radio.length; i++){
if(radio[i].checked) console.log("coffee selected : " + radio[i].value);
}
var checklist = document.getElementsByClassName("c1");
for(i=0;i<checklist.length;i++){
if (checklist[i].checked == true) console.log("Music selected : " + checklist[i].value);
}
</SCRIPT>
<FORM NAME="selectForm">
<B>Which Music types do you like?</B>
<input type="checkbox" class="c1" id="c1" value="blues">Blues</input>
<input type="checkbox" class="c1" id="c2" value="classical">Classical</input>
<input type="checkbox" class="c1" id="c3" value="opera">Opera</input>
<b>Choose Coffee to go with your music!</b><br>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="cappuchino">Cappuchino </input>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="latte">Latte</input>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="Mocha">Mocha</input>
<INPUT TYPE="button" VALUE="Which option selected?" onClick="valSelected()">
</FORM>
Regular Expressions
• A regular expression is an object that describes a pattern of characters.
Its matched against a text string, when you perform searches & replacements
Perform client-side data validations or any other extensive text entry parsing
RegExp objects may be created either with the RegExp() constructor or using a special
literal syntax.
regular expression literals are specified as characters within a pair of slash (/)
var
Eg
re = /web/gi expression is both case-insensitive and global
• \B Word Non-Boundary:
Get a match when it is not at the beginning or end of a word in the string
o /\Bor/ matches “normal” but not “origami”
o /or\B/ matches “normal” and “origami” but not “traitor”
o /\Bor\B/ matches “normal” but not “origami” or “traitor”
RegEx – Special Characters (Contd.)
• \d Numeral: Find any single digit 0 through 9
o /\d\d\d/ matches “212” and “415” but not “B17”
• [^…] Negated Character Set: any character not in the specified character set
o /[^AN]BC/ matches “BBC” and “CBC” but not “ABC” or “NBC”
• Positional Metacharacters
• “^” - At the beginning of a string or line
o /^Fred/ matches “Fred is OK” but not “I’m with Fred” or “Is Fred here?”
• “$” - At the end of a string or line
o /Fred$/ matches “I’m with Fred” but not “Fred is OK” or “Is Fred here?”
RegEx – Counting Metacharacters
Method Description
executes a search for a match in a string. It returns an array of information or null
exec() on a mismatch.
test() tests for a match in a string. It returns true or false
executes a search for a match in a string. It returns an array of information or null
match() on a mismatch.
search() tests for a match in a string; returns the index of the match, or -1 if search fails
executes a search for a match in a string, and replaces the matched substring with
replace() a replacement substring.
split() uses a reg exp or a fixed string to break a string into an array of substrings.
var pattern = /java/g;
var text = "JavaScript is more fun than java!";
var result = pattern.exec(text)
console.log(result) //["java", index: 28, input: "JavaScript is more fun than java!"]
When there’s a "g" flag, then str.match returns an array of all matches. There are no
additional properties in that array, and parentheses do not create any elements.
With no “g” flag, looks for the first match only.
Why Ajax?
• Intuitive and natural user interaction
• No clicking required. Call can be triggered on any event
• Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and refresh" user interaction
model
• Only user interface elements that contain new information are updated (fast
response)
• The rest of the user interface remains displayed as it is without interruption
(no loss of operational context)
XMLHttpRequest
• JavaScript object - XMLHttpRequest object for asynchronously exchanging the
XML data between the client and the server
• XMLHttpRequest Methods
open(“method”, “URL”, syn/asyn) : Assigns destination URL, method, mode
send(content) : Sends request including string or DOM object data
abort() : Terminates current request
getAllResponseHeaders() : Returns headers (labels + values) as a string
getResponseHeader(“header”) : Returns value of a given header
setRequestHeader(“label”,”value”) : Sets Request Headers before sending
• XMLHttpRequest Properties
Onreadystatechange : Event handler that fires at each state change
readyState values – current status of request
Status : HTTP Status returned from server: 200 = OK
responseText : get the response data as a string
responseXML : get the response data as XML data
Creating an AJAX application
• Step 1: Get an instance of XHR object
xhr.open("POST", "AddNos.jsp");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("tno1=100&tno2=200");
httpRequest.onreadystatechange = function(){
// process the server response
};
Ajax Demo
AJAX Demo with XML
AJAX Demo with JSON
JQUERY
Software
• Why jQuery
JavaScript is great for a lot of things especially manipulating the DOM but it’s pretty
complex stuff. DOM manipulation is by no means straightforward at the base level,
and that’s where jQuery comes in. It abstracts away a lot of the complexity involved in
dealing with the DOM, and makes creating effects super easy.
It can locate elements with a specific class
It can apply styles to multiple elements
It solves the cross browser issues
It supports method chaining
It makes the client side development very easy
Including jQuery in HTML Document
<html>
<head>
<title>Test jQuery</title>
<script type="text/javascript" src="jquery-3.5.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('Hi');
});
</script>
</head>
<body>
Welcome to jQuery
</body>
</html>
$(function() {
// jQuery code
});
Introduction to selectors
• jQuery uses same CSS selectors used to style html page to manipulate elements
CSS selectors select elements to add style to those elements where as jQuery selectors
select elements to add behavior to those elements.
Selectors allow page elements (Single or Multiple) to be selected.
• Selector Syntax
$(selectorExpression)
jQuery(selectorExpression)
$(selector).action()
Selectors
• Selecting by Tag Name:
• Selecting single tag takes the following syntax
$(‘p’) – selects all <p> elements
$(‘a’) – selects all <a> elements
• To reference multiple tags, use the ( , ) to separate the elements
$(‘p, a, span’) - selects all paragraphs, anchors and span elements
• Selecting Descendants
• $(‘ancestor descendant’) - selects all the descendants of the ansector
$(‘table tr’) - Selects all tr elements that are the descendants of the table element
• Descendants can be children, grand children etc of the designated ancestor
element.
Demo
Selecting by Element ID
• It is used to locate the DOM element very fast.
• Use the # character to select elements by ID
$("#first") — selects the element with id="first"
$(‘#myID’) – selects the element with id=" myID "
Selecting Elements by Class Name
• Use the ( . ) character to select elements by class name
$(".intro") — selects all elements with class="intro"
• To reference multiple tags, use the ( , ) character to separate class name.
$(‘.blueDiv, .redDiv’) - selects all elements containing class blueDiv and redDiv
• Tag names can be combined with elements name as well.
$(‘div.myclass’) – selects only those <div> tags with class=“myclass”
Selecting by attribute values
• Use brackets [attribute] to select on attribute name and/or attribute value
$(‘a[title]’) - selects all anchor elements that have a title attribute
$(‘a[title=“trainer”]’) – selects all <a> elements that have a “trainer” title attribute value
Selecting by input elements
• To select input elements of type : <input>:
$('input[type="text"]').css("background", "yellow");
• The index-related selectors (:eq(), :lt(), :gt(), :even, :odd) filter the set of elements
that have matched the expressions that precede them.
They narrow the set down based on the order of the elements within this matched set.
Eg, if elements are first selected with a class selector (.myclass) and four elements are
returned, these elements are given indices 0 through 3
• eq() - Select the element at index n within the matched set.
Eg : $("p:eq(1)") - Select the second <p> element
Eg : $("element:eq(0)") is same as $(‘element:first-child’)
• :gt() and lt() - Select all elements at an index > or < index within the matched set
Eg : $("tr:gt(3)") : Select all <tr> elements after the 4 first
Eg : $("tr:lt(4)") : Select the 4 first <tr> elements
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
<script>
$( "td:eq( 2 )" ).css( "color", "red" );
//$( "tr:first" ).css( "font-style", "italic" ); //is same as below line
$( "tr:eq(0)" ).css( "font-style", "italic" );
$( "td:gt(4)" ).css( "backgroundColor", "yellow" );
</script>
<script type="text/javascript">
$(document).ready(function() {
$('tr:odd').css('background-color','tomato');
$('tr:even').css('background-color','bisque');
});
</script>
<table border=1 cellspacing=5 cellpadding=5>
<th>column 1<th>column 2<th>column 3
<tr><td>data 1</td><td>data 2</td><td>data 3
<tr><td>data 4<td>data 5<td>data 6
<tr><td>data 7<td>data 8<td>data 9
<tr><td>data 10<td>data 11<td>data 12
</table>
Basic Filters continued
• :first , :last - Selects the first/last matched element.
:first is equivalent to :eq( 0 ) and :lt(1). This matches only a single element, whereas, :first-
child can match more than one; one for each parent.
• :header - Selects all elements that are headers, like h1, h2, etc
Basic Filters continued
• :not - Selects all elements that do not match the given selector.
Eg : $("p:not(.intro)") - Select all <p> elements except those with class="intro"
Eg : $('a:not(div.important a, a.nav)'); - // Selects anchors that do not reside within
'div.important' or have the class 'nav’
Child Filter
• $(‘element:first-child’) and $(‘element:last-child’) selects the first child & last child
of its parent.
$(‘span:first-child’) returns the span which is a first child for all the groups
• :nth-child() - Selects all elements that are the nth-child of their parent. 1-based
indexing
Eg : $("p:nth-child(3)") - Select each <p> element that is the third child of its parent
Content Filters
• :contains() will select elements that match the contents.
$(‘div:contains(“hello”)’) - selects div’s which contains the text hello (match is case
sensitive)
• :empty - Select all elements that have no children (incl text nodes)
• :has : Selects elements which contain at least one element that matches the
specified selector.
Eg : $("p:has(span)") - Select all <p> elements that have a <span> element inside of
them
Eg : $("div:has(p,span,li)").css("border","solid red"); - Select all <div> elements that have
at least one of the given elements inside
• :parent - Select all elements that have at least one child node (either an element
or text).
Eg : $("td:parent") - Select all <td> elements with children, including text
jQuery Traversing -> filtering
• .eq() - Reduce the set of matched elements to the one at the specified index.
Eg : $("p").eq(1).css("background-color","yellow") - Select the second <p> element (index
number 1)
• .filter() - Reduce the set of matched elements to those that match the selector or
pass the function's test
Eg : $("p").filter(".intro") - Return all <p> elements with class "intro“
• .first() / last()
Eg : $("div p").first() - Select first <p> element inside first <div> element
• .has() - Reduce the set of matched elements to those that have a descendant that
matches the selector or DOM element.
Eg : $("p").has("span") - Return all <p> elements that have <span> element inside
jQuery Traversing -> Tree Traversal
• Instead of doing that and running $(“div”) three times, you could do this:
$("div").fadeOut().css("color", "red").text("hello world");
Iterating through Nodes
• .each(function(index,Element)) is used to iterate through jQuery objects.
jQuery 3 also allows to iterate over the DOM elements of a jQuery collection using the
for...of loop.
Working with Attributes
• Object attributes can be used using attr():
var val = $(‘#customDiv’).attr(‘title’); - Retrieves the title attribute value
$.html() treats the string as HTML, $.text() treats the content as text
Getting Content
mouseup()
mouseover()
keydown()
keypress()
hover() : hover() method takes two functions
and is a combination of the mouseenter() $("#p1").hover(function(){
and mouseleave() methods. alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
Handling Click Events
• .click(handler([eventObject])) is used to listen for a click event or trigger a click
event on an element
$(‘#submitButton’).click(function() { alert(‘Clicked’) });
Using on() and off()
• The on() method attaches one or more event handlers for the selected elements.
$("#flip").click(function(){
$("#panel").slideDown();
});
jQuery Fading Effects
• The jQuery fade methods gradually change the opacity for selected elements.
• jQuery has the following fade methods:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
• The speed parameter can take the following values: "slow", "fast", "normal", or
milliseconds.
The opacity parameter in the fadeTo() method allows fading to a given opacity.
The callback parameter is the name of a function to be executed after the function
completes.
$('.blueDiv').fadeTo(1000,0.1,function(){
$('#results').text('FadeTo Animation Completed');
});
Creating Custom Animation
• Custom animation can be created in jQuery with the animate() function
animate(params, duration, callback)
o params contains the properties of the object you’re animating, such as CSS properties, duration is
the optional time in milliseconds that the animation should take and callback is an optional
callback function.
<style type="text/css">
#content { background-color:#ffaa00; width:300px; height:30px; padding:3px; }
</style>
<script type="text/javascript">
$(document).ready(function() {
$("#animate").click(function() {
$("#content").animate({"height": "100px", "width": "350px"}, "slow");
});
});
</script>
</head>
<body>
<input type="button" id="animate" value="Animate"/>
<div id="content">Animate Height</div> </body>
jQuery Ajax features
$.get('GetContents.html',function(data){
$('#targetDiv').html(data);
},'html');
$.getJSON('GetContents.aspx,{id:5},function(data){
$('#targetDiv').html(data);
});
$.ajax({
url: “employee.asmx/GetEmployees",
data : null,
contentType: "application/json; charset=utf-8",
datatype: ‘json’,
success: function(data,status,xhr){
//Perform success operation
},
error: function(xhr,status,error) {
//show error details
}
});