SlideShare a Scribd company logo
Java Script and HTML
HTML
• HTML stands for Hyper Text Markup Language
• HTML describes the structure of a Web page
• HTML consists of a series of elements
• HTML elements tell the browser how to display the content
• HTML elements are represented by tags
• HTML tags label pieces of content such as "heading", "paragraph", "table", and so
on
• Browsers do not display the HTML tags, but use them to render the content of
the page
• What is Website, WebPage and Internet
Use of html
• First developed by Tim Berners-Lee in 1990, HTML is short for
HyperText Markup Language. HTML is used to create electronic
documents (called pages) that are displayed on the World Wide Web.
Each page contains a series of connections to other pages called
hyperlinks.
First HTML PAGE
• <!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
HTML Document
•The <!DOCTYPE html> declaration defines this document to
be HTML5
•The <html> element is the root element of an HTML page
•The <head> element contains meta information about the
document
•The <title> element specifies a title for the document
•The <body> element contains the visible page content
•The <h1> element defines a large heading
•The <p> element defines a paragraph
HTML Tags
HTML Tags
HTML tags are element names surrounded by angle brackets:
<tagname>content goes here...</tagname>
•HTML tags normally come in pairs like <p> and </p>
•The first tag in a pair is the start tag, the second tag is the end tag
•The end tag is written like the start tag, but with a forward slash inserted before the
tag name
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading.
<h6> defines the least important heading:
Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Links
HTML links are defined with the <a> tag:
Example
<a href="https://www.w3schools.com">This is a link</a>
HTML Images
HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height
are provided as attributes:
Example
<img src=“day01.jpg" alt="W3Schools.com" width="104" height="142">
Create HTML Document
• Till now
HTML Active Controls
HTML Buttons
HTML buttons are defined with the <button> tag:
Example
<button>Click me</button>
HTML ListsHTML lists are defined with the <ul> (unordered/bullet list) or the <ol> (ordered/numbered
list) tag, followed by <li> tags (list items):
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
Empty HTML Elements
HTML elements with no content are called empty
elements.
<br> is an empty element without a closing tag (the
<br> tag defines a line break):
Example
<p>This is a <br> paragraph with a line
break.</p>
HTML Attributes
• All HTML elements can have attributes
• Attributes provide additional information about an element
• Attributes are always specified in the start tag
• Attributes usually come in name/value pairs like: name="value“
• <a href="https://www.w3schools.com">This is a link</a>
• <img src="img_girl.jpg" width="500" height="600">
• <p style="color:red">This is a paragraph.</p>
• <p title="I'm a tooltip">
This is a paragraph.
</p>
• <p title='John "ShotGun" Nelson'>
Create HTML
• Till now
The HTML Style Attribute
Setting the style of an HTML element, can be done with the
style attribute.
The HTML style attribute has the following syntax:
<tagname style="property:value;">
The property is a CSS property. The value is a CSS value.
Background Color
The CSS background-color property defines the background color
for an HTML element.
This example sets the background color for a page to powderblue:
Example
<body style="background-color:powderblue;">
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
Text Color
The CSS color property defines the text color for an HTML element:
Example
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
Text Size
The CSS font-size property defines the text size for an HTML
element:
Example
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>
Text Alignment
The CSS text-align property defines the horizontal text
alignment for an HTML element:
Example
<h1 style="text-align:center;">
Centered Heading</h1>
<p style="text-align:center;">
Centered paragraph.</p>
In the previous chapter, you learned about the HTML style attribute.
HTML also defines special elements for defining text with a special meaning.
HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
Formatting elements were designed to display special types of text:
•<b> - Bold text
•<strong> - Important text
•<i> - Italic text
•<em> - Emphasized text
•<mark> - Marked text
•<small> - Small text
•<del> - Deleted text
•<ins> - Inserted text
•<sub> - Subscript text
•<sup> - Superscript text
Quotes, Abbr and Address
• <p>Here is a quote from WWF's website:</p>
<blockquote cite="http://www.worldwildlife.org/who/index.html">
For 50 years, WWF has been protecting the future of nature. The world's leading conservation organization, WWF
works in 100 countries and is supported by 1.2 million members in the United States and close to 5 million globally.
</blockquote>
• Abbreviation
• <p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>
• Address
• <address>
Written by John Doe.<br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland<br>
USA
</address>
Create HTML
• Till now
HTML Colors
Background / Foreground Color
•Example
•<h1 style="background-color:DodgerBlue;">Hello
World</h1>
<p style="background-color:Tomato;">Lorem ipsum...</p>
•Text Color
• <h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>
Border Color
• You can set the color of borders:
• Hello World
• Hello World
• Hello World
• Example
• <h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>
HyperLinks
• HTML links are hyperlinks.
• You can click on a link and jump to another document.
• When you move the mouse over a link, the mouse arrow will turn
into a little hand.
• Note: A link does not have to be text. It can be an image or any other
HTML element.
• <a href="url">link text</a>
• <a href="html_images.asp">HTML Images</a>
Styles, StyleSheets, CSS
Styling HTML with 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.
CSS can be added to HTML elements in 3 ways:
•Inline - by using the style attribute in HTML elements
•Internal - by using a <style> element in the <head> section
•External - by using an external CSS file
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
This example sets the text color of the <h1> element to blue:
Example
<h1 style="color:blue;">This is a Blue Heading</h1>
Internal CSS
An internal CSS is used to define a style for a single HTML page.
An internal CSS is defined in the <head> section of an HTML page, within a <style> element:
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1> <p>This is a paragraph.</p>
</body>
</html>
External CSSAn external style sheet is used to define the style for many HTML pages.
With an external style sheet, you can change the look of an entire web site, by
changing one file!
To use an external style sheet, add a link to it in the <head> section of the HTML page:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
StyleSheet Attributes
•Use the HTML style attribute for inline styling
•Use the HTML <style> element to define internal CSS
•Use the HTML <link> element to refer to an external CSS file
•Use the HTML <head> element to store <style> and <link> elements
•Use the CSS color property for text colors
•Use the CSS font-family property for text fonts
•Use the CSS font-size property for text sizes
•Use the CSS border property for borders
•Use the CSS padding property for space inside the border
•Use the CSS margin property for space outside the border
• <style>
a:link {
color: green; background-color: transparent; text-decoration: none;
}
a:visited {
color: pink; background-color: transparent; text-decoration: none;
}
a:hover {
color: red; background-color: transparent; text-decoration: underline;
}
a:active {
color: yellow;
background-color: transparent;
text-decoration: underline;
}
Style for Hyperlink
HTML Links - The target Attribute
The target attribute specifies where to open the linked document.
The target attribute can have one of the following values:
•_blank - Opens the linked document in a new window or tab
•_self - Opens the linked document in the same window/tab as it
was clicked (this is default)
•_parent - Opens the linked document in the parent frame
•_top - Opens the linked document in the full body of the window
•framename - Opens the linked document in a named frame
<a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>
Create HTML
• Till now
HTML Images
• <!DOCTYPE html>
<html>
<head>
<style>
img {
width: 100%;
}
</style>
</head>
<body>
<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
</body>
</html>
The width, height, and style attributes are valid in HTML.
However, we suggest using the style attribute. It prevents styles sheets from changing the size of images:
Image Maps
The <map> tag defines an image-map. An image-map is an image with clickable areas.
In the image below, click on the computer, the phone, or the cup of coffee:
<img src="workplace.jpg" alt="Workplace" usemap="#workmap">
<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>
Section 02
Tables (HTML)
JavaScript
Table
Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria
Island Trading Helen Bennett UK
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy
Example
• <table style="width:100%">
<tr>
<th>Firstname</th> <th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td> <td>Smith</td> <td>50</td>
</tr>
<tr>
<td>Eve</td> <td>Jackson</td> <td>94</td>
</tr>
</table>
HTML Table - Adding a Border
If you do not specify a border for the table, it will be displayed
without borders.
A border is set using the CSS border property:
Example
table, th, td {
border: 1px solid black;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
HTML Table - Left-align Headings
By default, table headings are bold and centered.
To left-align the table headings, use the CSS text-align prop
Example
th {
text-align: left;
}
HTML Table - Cells that Span Many Columns
To make a cell span more than one column, use the colspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>55577854</td>
<td>55577855</td>
</tr>
</table>
HTML Table - Cells that Span Many Rows
To make a cell span more than one row, use the rowspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>55577854</td>
</tr>
<tr>
<td>55577855</td>
</tr>
</table>
HTML Table - Adding a Caption
To add a caption to a table, use the <caption> tag:
Example
<table style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th> <th>Savings</th>
</tr>
<tr>
<td>January</td> <td>$100</td>
</tr>
<tr>
<td>February</td> <td>$50</td>
</tr>
javaScript
• Why Study JavaScript?
• JavaScript is one of the 3 languages all web developers must learn:
• 1. HTML to define the content of web pages
• 2. CSS to specify the layout of web pages
• 3. JavaScript to program the behavior of web pages
First JavaScript
• <!DOCTYPE html>
• <html>
• <body>
• <h2>JavaScript in Body</h2>
• <p id="demo"></p>
• <script>
• document.getElementById("demo").innerHTML = "My
First JavaScript";
• </script>
• </body>
JavaScript Function
• <!DOCTYPE html>
<html><head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
• <h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
• </body>
</html>
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with
id="demo") and changes the element content (innerHTML) to
"Hello JavaScript":
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>
Light bulb
• <!DOCTYPE html>
• <html>
• <body>
• <h2>What Can JavaScript Do?</h2>
• <p>JavaScript can change HTML attribute values.</p>
• <p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
• <button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
• <img id="myImage" src="pic_bulboff.gif" style="width:100px">
• <button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>
• </body>
• </html>
Changing html cstyle
• <!DOCTYPE html>
• <html>
• <body>
• <h2>What Can JavaScript Do?</h2>
• <p id="demo">JavaScript can change the style of an HTML element.</p>
• <button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
• </body>
• </html>
Hiding html content
• <!DOCTYPE html>
• <html>
• <body>
• <h2>What Can JavaScript Do?</h2>
• <p id="demo">JavaScript can hide HTML elements.</p>
• <button type="button"
onclick="document.getElementById('demo').style.display='none'">Click
Me!</button>
• </body>
• </html>
External Call of JavaScript
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
Example
<script src="myScript.js"></script>
Try it Yourself »
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is located.
External scripts cannot contain <script> tags.
CODE
• <!DOCTYPE html>
• <html>
• <body>
• <h2>External JavaScript</h2>
• <p id="demo">A Paragraph.</p>
• <button type="button"
onclick="myFunction()">Try it</button>
• <p>(myFunction is stored in an external file
called "myScript.js")</p>
• <script src="Script1.js"></script>
• </body>
// JavaScript source code
function myFunction() {
document.getElementById("demo").inner
HTML = "I am called from external file";
}
External JavaScript Advantages
• Placing scripts in external files has some advantages:
• It separates HTML and code
• It makes HTML and JavaScript easier to read and maintain
• Cached JavaScript files can speed up page loads
• To add several script files to one page - use several script tags:
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
•Writing into an HTML element, using innerHTML.
•Writing into the HTML output using document.write()
•Writing into an alert box, using window.alert().
•Writing into the browser console, using console.log(
1. Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
2. Document write
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
3. window.alert()
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Semicolons ;
• Semicolons separate JavaScript statements.
• Add a semicolon at the end of each executable
statement:
• var a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
• When separated by semicolons, multiple statements on
one line are allowed:
• a = 5; b = 6; c = a + b;
• <!DOCTYPE html>
• <html>
• <body>
• <h2>JavaScript Statements</h2>
• <p>Multiple statements on one line is allowed.</p>
• <p id="demo1"></p>
• <script>
• var a, b, c;
• a = 5; b = 6; c = a + b;
• document.getElementById("demo1").innerHTML = c;
• </script></body>
• </html>
Code blocks
• <!DOCTYPE html>
• <html>
• <body>
• <h2>JavaScript Statements</h2>
• <p>JavaScript code blocks are written between { and }</p>
• <button type="button" onclick="myFunction()">Click Me!</button>
• <p id="demo1"></p> <p id="demo2"></p>
• <script>
• function myFunction() {
• document.getElementById("demo1").innerHTML = "Hello COMSATS!";
• document.getElementById("demo2").innerHTML = “How are all?";
• }
• </script></body>
• </html>
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if
available) the debugging function
do ... while Executes a block of statements, and repeats the
block, while a condition is true
for Marks a block of statements to be executed, as
long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed,
depending on a condition
return Exits a function
switch Marks a block of statements to be executed,
depending on different cases
try ... catch Implements error handling to a block of
statements
var Declares a variable
JS Strings
• <html> <body>
• <h2>JavaScript Strings</h2>
• <p>You can use quotes inside a string, as long as they don't match the quotes
surrounding the string.</p>
• <p id="demo"></p>
• <script>
• var answer1 = "It's alright";
• var answer2 = "He is called 'Johnny'";
• var answer3 = 'He is called "Johnny"';
• document.getElementById("demo").innerHTML =
• answer1 + "<br>" + answer2 + "<br>" + answer3;
• document.getElementById("demo").innerHTML = "<br>" + "String length is " +
answer3.length;
• </script></body> </html>
Special Characters
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the backslash escape character.
The backslash () escape character turns special characters into string characters:
Code Result Description
' ' Single quote
" " Double quote
  Backslash
<body>
<h2>JavaScript Strings</h2>
<p>The escape sequence " inserts a double quote in a string.</p>
<p id="demo"></p>
<script>
var x = "We are the so-called "Vikings" from the north.";
document.getElementById("demo").innerHTML = x;
</script>
</body>
Strings Can be Objects
Normally, JavaScript strings are primitive values, created from literals:
var firstName = “xyz";
But strings can also be defined as objects with the keyword new:
var firstName = new String(“xyz");
Example
var x = “xyz";
var y = new String(“xyz");
// typeof x ??
// typeof y ??
String Methods
Finding a String in a String
The indexOf() method returns the index of (the position of) the first occurrence
of a specified text in a string:
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
Searching for a String in a String
The search() method searches a string for a specified value and returns the position
of the match:
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Extracting String Parts
There are 3 methods for extracting a part of a string:
•slice(start, end)
•substring(start, end)
•substr(start, length)
•Replace (“old text”,”new text”)
String Methods
• String.toUpperCase() and String.toLowerCase()
• String.Concat() or use + Operator
• String.trim()
• String.charAt(SomeIndex)
• String.charCodeAt(someindex) returns ASCII Code
• String[index] or String[index] = ‘x’
• Split ()
• var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|");
JS Arrays
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Array Elements Can Be Objects
• JavaScript variables can be objects. Arrays are special
kinds of objects.
• Because of this, you can have variables of different types
in the same Array.
• You can have objects in an Array. You can have functions
in an Array. You can have arrays in an Array:
• myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods
The real strength of JavaScript arrays are the
built-in array properties and methods:
Examples
var x = cars.length; // The length property
returns the number of elements
var y = cars.sort(); // The sort() method
sorts arrays
Looping through Arrays
• <body>
• <h2>JavaScript Arrays</h2>
• <p>The best way to loop through an array is using a standard for loop:</p>
• <p id="demo"></p>
• <script>
• var fruits, text, fLen, i;
• fruits = ["Banana", "Orange", "Apple", "Mango"];
• fruits.push("Lemon"); fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
• fLen = fruits.length;
• text = "<ul>";
• for (i = 0; i < fLen; i++) {
• text += "<li>" + fruits[i] + "</li>"; }
• text += "</ul>";
• document.getElementById("demo").innerHTML = text;
• </script>
• </body>
Sorting Arrays
• <body>
• <h2>JavaScript Array Sort</h2>
• <p>Click the buttons to sort the array alphabetically or numerically.</p>
• <button onclick="myFunction1()">Sort Alphabetically</button>
• <button onclick="myFunction2()">Sort Numerically</button>
• <p id="demo"></p>
• <script>
• var points = [40, 100, 1, 5, 25, 10];
• document.getElementById("demo").innerHTML = points;
• function myFunction1() {
• points.sort();
• document.getElementById("demo").innerHTML = points; }
• function myFunction2() {
• points.sort(function (a, b) { return a - b });
• document.getElementById("demo").innerHTML = points;
• } </script> </body>
JS Dates
Date objects are created with the new Date() constructor.
There are 4 ways to create a new date object:
new Date()
new Date(year, month, day, hours, minutes, seconds, mill
new Date(milliseconds)
new Date(date string)
Date methods
Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1,
1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.
Date methods
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript getMonth()</h2>
<p>The getMonth() method returns the month as a number:</p>
<p>You can use an array to display the name of the month:</p>
<p id="demo"></p>
<script>
var d = new Date();
var months =
["January","February","March","April","May","June","July","August","September","October","Novembe
r","December"];
document.getElementById("demo").innerHTML = months[d.getMonth()];</script>
</body>
</html>
JavaScript Form Validation
• HTML form validation can be done by JavaScript.
• If a form field (fname) is empty, this function alerts a message, and returns false,
to prevent the form from being submitted:
• JavaScript Example
• function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Number Validation
• <script>
• function myFunction() {
• var x, text;
• // Get the value of the input field with id="numb"
• x = document.getElementById("numb").value;
• // If x is Not a Number or less than one or greater than 10
• if (isNaN(x) || x < 1 || x > 10) {
• text = "Input not valid";
• } else {
• text = "Input OK";
• } document.getElementById("demo").innerHTML = text;
• }
• </script>
Constraint Validation HTML Input Attributes
Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type Specifies the type of an input element
Constraint Validation DOM
• If an input field contains invalid data, display a message:
• The checkValidity() Method
• <input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}
}
</script>
Property Description
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Sets the validationMessage property of an input element.
JS Animation
• D yourself
JavaScript vs React.JS
• Web apps are becoming increasingly complex and dynamic. In
response, new tools and libraries like React have been created to
speed up the process.
• But how is developing a web app with React different than developing
an app with just plain JavaScript?
JavaScript
• To set some boundaries, let’s first define what we mean by "plain"
JavaScript (also called "vanilla" JavaScript).
• React is a library that defines the way apps are written. It does this by
setting very clear rules about how data can flow through the app, and
how the UI will adapt as a result of that changing data. There are
other libraries that set similar boundaries, such as Angular and Vue.
• Plain JavaScript (that is, JavaScript written without libraries) on the
other hand, doesn’t set any rules about how data can be defined, or
how the UI can be changed. That makes apps written without these
libraries more freeform and customizable. But going this route can
also lead to problems down the road
The major differences
Since there are so many ways to write vanilla JS, it can be difficult to pin
down a list of differences that applies to 100% of apps. But here we’ll
define some key differences that apply to many plain JS apps that are
written without a framework.
• How the user interface is first created
• How functionality is split up across the app
• How data is stored on the browser
• How the UI is updated
In plain JS, the initial user interface is generally created in HTML
on the server. Meaning,
HTML is dynamically created on the server, and might look
something like this:
<div>
<h1>Grocery List</h1>
<ul>
<li>Milk</li>
<li>Bread</li>
<li>Eggs</li>
</ul>
</div>
That gets sent to the web browser and displayed—no JavaScript needed yet!
In contrast, a React app will start with a fixed HTML file that looks like this:
<div id=“root”></div>
How the user interface is first created
UI in REACT
Instead of defining the initial UI on the server, the UI gets defined on the browser. So the app starts with a blank
container (a div in this case), and then the UI gets loaded into that container. The UI is defined by a component that
returns JSX. JSX looks like HTML, but is actually JavaScript - and might look like this:
function GroceryList(props) {
return (
<div>
<h1>Grocery List</h1>
<ul>
<li>Milk</li>
<li>Bread</li>
<li>Eggs</li>
</ul>
</div>
)
};
And that new GroceryList component gets mounted (or "rendered") into the div container using a library called ReactDOM:
<GroceryList />, <GroceryList />, <GroceryList />, document.getElementById("root")
This results in the same initial UI as the plain JS example above except that happens on the browser, instead of
beforehand on the server.
How functionality is split up across the app
With a plain JS app, there are no requirements about how you split up
functionality or UI components in an application. For example, our initial
grocery list can just be defined in a main index.html file:
<div>
<h1>Grocery List</h1>
<ul id="grocery-list">
<li>Milk</li>
<li>Bread</li>
<li>Eggs</li>
</ul>
</div>
And the code that updates the list might be buried deep in a separate javascript file:
function addItemToList() {
// Add item
}
JS Enforces Different Jscript code to open
from all files
• React enforces that your app is split into components and that each one of those components maintains
all of the code needed to both display and update the UI:
function GroceryList(props) {
function addItem() {
// Add Item
}
return (
<div>
<h1>Grocery List</h1>
<ul>
<li>Milk</li>
<li>Bread</li>
<li>Eggs</li>
</ul>
</div>
)
};
Main Advantages
•This keeps the update code right next to the
display code, and makes complicated apps easier
to understand.
•It also allows for greater code reuse since
generic components can be made and shared
across an app.
Data storage on browser
• Once the initial UI is loaded, the user will be able to interact with your
app. For interactions like typing into an input box, that text has to be
stored somewhere on the browser before it can be used later (to submit
to the backend server, for example).
• In a plain JS app, that user data is generally stored in the DOM
(Document Object Model).
• The Document Object Model (DOM) is created and maintained by the
browser itself and represents all of the HTML nodes on the entire page.
That includes any data stored on those nodes.
<input type="text" placeholder="Enter an item" id="item-input" />
Change in Value
• for just one input change in Jscript not difficult, but it can get tedious for an
entire form. Plus if the id of the input changes, you’ll have to make sure to
change it in every single spot where you access that id as well.
• In contrast, React uses a technique called "controlled components" to set
the text value in a JavaScript object as the user types it.
• First, a bit of state has to be defined to hold the input value:
const [itemInput, setItemInput] = useState("");
Input ID change in REACT
• And then that set has to be set whenever the input changes. That
makes the input box code more complex
• <input type="text" placeholder="Enter an item" value={itemInput}
onChange={e => setItemInput(e.target.value)}
JS Animation
• Timer
let timer = setInterval(function() {
if (animation complete)
clearInterval(timer);
else increase style.left by 2px}, 20);
// change by 2px every 20ms, about 50 frames per second
Train Animation
let start = Date.now(); // remember start time let
timer = setInterval(function()
{ // how much time passed from the start?
Let imePassed = Date.now() - start;
if (timePassed >= 2000)
{ clearInterval(timer);
// finish the animation after 2 seconds return;
} // draw the animation at the moment timePassed
draw(timePassed); }, 20);
// as timePassed goes from 0 to 2000
// left gets values from 0px to 400px
function draw(timePassed)
{ train.style.left = timePassed / 5 + 'px'; }
Interval Timer
setInterval(function() { animate1(); animate2(); animate3(); }, 20)
Let’s imagine we have several animations running simultaneously.
If we run them separately, then even though each one has setInterval(..., 20), then the browser would
have to repaint much more often than every 20ms.
That’s because they have different starting time, so “every 20ms” differs between different animations. The
intervals are not aligned. So we’ll have several independent runs within 20ms.
As Code Shows
setInterval(animate1, 20);
// independent animations
setInterval(animate2, 20); // in different places of the script
setInterval(animate3, 20);
The better approach is one central timer with one stopwatch
Animation when inactive webpages
These several independent redraws should be grouped together, to make the redraw easier for the
browser and hence load less CPU load and look smoother.
There’s one more thing to keep in mind. Sometimes when CPU is overloaded, or there are other
reasons to redraw less often (like when the browser tab is hidden), so we really shouldn’t run it
every 20ms.
But how do we know about that in JavaScript? There’s a specification Animation timing that provides
the function requestAnimationFrame. It addresses all these issues and even more.
let requestId = requestAnimationFrame(callback)
That schedules the callback function to run in the closest time when the browser wants to do animation.
If we do changes in elements in callback then they will be grouped together with other requestAnimationFrame callbacks and with
CSS animations. So there will be one geometry recalculation and repaint instead of many.
The returned value requestId can be used to cancel the call:
// cancel the scheduled execution of callback cancelAnimationFrame(requestId);
Better Animation Approach
<script>
let prev = performance.now();
let times = 0; requestAnimationFrame(function measure(time)
{ document.body.insertAdjacentHTML("beforeEnd",
Math.floor(time - prev) + " ");
prev = time;
if (times++ < 10) requestAnimationFrame(measure); })
</script>
Structure Animation Function
function animate({timing, draw, duration})
{ let start = performance.now();
requestAnimationFrame(function animate(time)
{ // timeFraction goes from 0 to 1
let timeFraction = (time - start) / duration;
if (timeFraction > 1) timeFraction = 1;
// calculate the current animation state
let progress = timing(timeFraction) draw(progress);
// draw it
if (timeFraction < 1)
{ requestAnimationFrame(animate); }
} );
}
Animate Function
• Function animate accepts 3 parameters that essentially describes the
animation:
• duration
• Total time of animation. Like, 1000.
• timing(timeFraction)
• Timing function, like CSS-property transition-timing-function that gets the
fraction of time that passed (0 at start, 1 at the end) and returns the animation
completion .
• For instance, a linear function means that the animation goes on uniformly
with the same speed: function linear(timeFraction) {
return timeFraction;
}
Moving the element
draw(progress)
The function that takes the animation completion state and draws it.
The value progress=0 denotes the beginning animation state, and progress=1 – the end state.
This is that function that actually draws out the animation.
It can move the element:
function draw(progress) { train.style.left = progress + 'px'; }
The simple animate Code
animate({
duration: 1000,
timing(timeFraction) {
return timeFraction;
},
draw(progress) {
elem.style.width = progress * 100 + '%';
}
});
// This will call anima
Animate function in JS file
function animate({duration, draw, timing}) {
let start = performance.now();
requestAnimationFrame(function animate(time) {
let timeFraction = (time - start) / duration;
if (timeFraction > 1) timeFraction = 1;
let progress = timing(timeFraction)
draw(progress);
if (timeFraction < 1) {
requestAnimationFrame(animate);
}
});
}

More Related Content

What's hot

Introduction to Html by Ankitkumar Singh
Introduction to Html by Ankitkumar SinghIntroduction to Html by Ankitkumar Singh
Introduction to Html by Ankitkumar Singh
Ankitkumar Singh
 
What is HTML - An Introduction to HTML (Hypertext Markup Language)
What is HTML - An Introduction to HTML (Hypertext Markup Language)What is HTML - An Introduction to HTML (Hypertext Markup Language)
What is HTML - An Introduction to HTML (Hypertext Markup Language)
Ahsan Rahim
 
Html cia
Html ciaHtml cia
Html
HtmlHtml
Html
NithyaD5
 
HTML Basics 1 workshop
HTML Basics 1 workshopHTML Basics 1 workshop
HTML Basics 1 workshop
John Allan
 
HTML, CSS, JavaScript for beginners
HTML, CSS, JavaScript for beginnersHTML, CSS, JavaScript for beginners
HTML, CSS, JavaScript for beginners
PrakritiDhang
 
HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2
Sharon Wasden
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
Eliran Eliassy
 
Css module1
Css module1Css module1
Css module1
VARSHAKUMARI49
 
HTML5
HTML5 HTML5
Html 5
Html 5Html 5
Web fundamental concept and tags
Web fundamental concept and tags Web fundamental concept and tags
Web fundamental concept and tags
shameen khan
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5Terry Ryan
 
HTML Basics
HTML BasicsHTML Basics
HTML Basics
PumoTechnovation
 
(Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS (Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS
Dave Kelly
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
Sun Technlogies
 
Introduction to html course digital markerters
Introduction to html course digital markertersIntroduction to html course digital markerters
Introduction to html course digital markerters
SEO SKills
 

What's hot (20)

Introduction to Html by Ankitkumar Singh
Introduction to Html by Ankitkumar SinghIntroduction to Html by Ankitkumar Singh
Introduction to Html by Ankitkumar Singh
 
What is HTML - An Introduction to HTML (Hypertext Markup Language)
What is HTML - An Introduction to HTML (Hypertext Markup Language)What is HTML - An Introduction to HTML (Hypertext Markup Language)
What is HTML - An Introduction to HTML (Hypertext Markup Language)
 
Html cia
Html ciaHtml cia
Html cia
 
Html
HtmlHtml
Html
 
HTML Basics 1 workshop
HTML Basics 1 workshopHTML Basics 1 workshop
HTML Basics 1 workshop
 
HTML, CSS, JavaScript for beginners
HTML, CSS, JavaScript for beginnersHTML, CSS, JavaScript for beginners
HTML, CSS, JavaScript for beginners
 
HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
 
Lecture1and2
Lecture1and2Lecture1and2
Lecture1and2
 
Css module1
Css module1Css module1
Css module1
 
HTML5
HTML5 HTML5
HTML5
 
Html 5
Html 5Html 5
Html 5
 
Html2
Html2Html2
Html2
 
Unit 1wt
Unit 1wtUnit 1wt
Unit 1wt
 
Web fundamental concept and tags
Web fundamental concept and tags Web fundamental concept and tags
Web fundamental concept and tags
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
HTML Basics
HTML BasicsHTML Basics
HTML Basics
 
(Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS (Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
 
Introduction to html course digital markerters
Introduction to html course digital markertersIntroduction to html course digital markerters
Introduction to html course digital markerters
 

Similar to Java script and html

html
htmlhtml
html
tumetr1
 
HTML_css_web__tech___nology_______________.pptx
HTML_css_web__tech___nology_______________.pptxHTML_css_web__tech___nology_______________.pptx
HTML_css_web__tech___nology_______________.pptx
JoelJoseph961925
 
Html tutorials by www.dmdiploma.com
Html tutorials by www.dmdiploma.comHtml tutorials by www.dmdiploma.com
Html tutorials by www.dmdiploma.com
ShwetaAggarwal56
 
Computer application html
Computer application htmlComputer application html
Computer application html
PrashantChahal3
 
Html ppt
Html pptHtml ppt
Html ppt
Ruchi Kumari
 
Html Workshop
Html WorkshopHtml Workshop
Html Workshop
vardanyan99
 
4_5926925443935505826.pptx
4_5926925443935505826.pptx4_5926925443935505826.pptx
4_5926925443935505826.pptx
Lusi39
 
Html
HtmlHtml
Basic Html Knowledge for students
Basic Html Knowledge for studentsBasic Html Knowledge for students
Basic Html Knowledge for students
vethics
 
FEWDD Lec 1 web development presentation
FEWDD Lec 1 web development presentationFEWDD Lec 1 web development presentation
FEWDD Lec 1 web development presentation
NamitSeth3
 
Chapter 6 html
Chapter 6 htmlChapter 6 html
Chapter 6 html
home
 
SEO Training in Noida- Skyinfotech.in
SEO Training in Noida- Skyinfotech.inSEO Training in Noida- Skyinfotech.in
SEO Training in Noida- Skyinfotech.in
Sky Infotech
 
Html full
Html fullHtml full
Html full
GulshanKumar368
 
BITM3730 9-20.pptx
BITM3730 9-20.pptxBITM3730 9-20.pptx
BITM3730 9-20.pptx
MattMarino13
 
Html.docx
Html.docxHtml.docx
Html.docx
Noman Ali
 
HTML and CSS
HTML and CSSHTML and CSS
HTML and CSS
Ketan Ghumatkar
 
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptxDESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
bmit1
 
BITM3730 9-19.pptx
BITM3730 9-19.pptxBITM3730 9-19.pptx
BITM3730 9-19.pptx
MattMarino13
 
Html
HtmlHtml
introduction to front-end development with github.
introduction to front-end development with github.introduction to front-end development with github.
introduction to front-end development with github.
Abdul Salam
 

Similar to Java script and html (20)

html
htmlhtml
html
 
HTML_css_web__tech___nology_______________.pptx
HTML_css_web__tech___nology_______________.pptxHTML_css_web__tech___nology_______________.pptx
HTML_css_web__tech___nology_______________.pptx
 
Html tutorials by www.dmdiploma.com
Html tutorials by www.dmdiploma.comHtml tutorials by www.dmdiploma.com
Html tutorials by www.dmdiploma.com
 
Computer application html
Computer application htmlComputer application html
Computer application html
 
Html ppt
Html pptHtml ppt
Html ppt
 
Html Workshop
Html WorkshopHtml Workshop
Html Workshop
 
4_5926925443935505826.pptx
4_5926925443935505826.pptx4_5926925443935505826.pptx
4_5926925443935505826.pptx
 
Html
HtmlHtml
Html
 
Basic Html Knowledge for students
Basic Html Knowledge for studentsBasic Html Knowledge for students
Basic Html Knowledge for students
 
FEWDD Lec 1 web development presentation
FEWDD Lec 1 web development presentationFEWDD Lec 1 web development presentation
FEWDD Lec 1 web development presentation
 
Chapter 6 html
Chapter 6 htmlChapter 6 html
Chapter 6 html
 
SEO Training in Noida- Skyinfotech.in
SEO Training in Noida- Skyinfotech.inSEO Training in Noida- Skyinfotech.in
SEO Training in Noida- Skyinfotech.in
 
Html full
Html fullHtml full
Html full
 
BITM3730 9-20.pptx
BITM3730 9-20.pptxBITM3730 9-20.pptx
BITM3730 9-20.pptx
 
Html.docx
Html.docxHtml.docx
Html.docx
 
HTML and CSS
HTML and CSSHTML and CSS
HTML and CSS
 
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptxDESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
 
BITM3730 9-19.pptx
BITM3730 9-19.pptxBITM3730 9-19.pptx
BITM3730 9-19.pptx
 
Html
HtmlHtml
Html
 
introduction to front-end development with github.
introduction to front-end development with github.introduction to front-end development with github.
introduction to front-end development with github.
 

Recently uploaded

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 

Recently uploaded (20)

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 

Java script and html

  • 2. HTML • HTML stands for Hyper Text Markup Language • HTML describes the structure of a Web page • HTML consists of a series of elements • HTML elements tell the browser how to display the content • HTML elements are represented by tags • HTML tags label pieces of content such as "heading", "paragraph", "table", and so on • Browsers do not display the HTML tags, but use them to render the content of the page • What is Website, WebPage and Internet
  • 3. Use of html • First developed by Tim Berners-Lee in 1990, HTML is short for HyperText Markup Language. HTML is used to create electronic documents (called pages) that are displayed on the World Wide Web. Each page contains a series of connections to other pages called hyperlinks.
  • 4. First HTML PAGE • <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </body> </html>
  • 5. HTML Document •The <!DOCTYPE html> declaration defines this document to be HTML5 •The <html> element is the root element of an HTML page •The <head> element contains meta information about the document •The <title> element specifies a title for the document •The <body> element contains the visible page content •The <h1> element defines a large heading •The <p> element defines a paragraph
  • 6. HTML Tags HTML Tags HTML tags are element names surrounded by angle brackets: <tagname>content goes here...</tagname> •HTML tags normally come in pairs like <p> and </p> •The first tag in a pair is the start tag, the second tag is the end tag •The end tag is written like the start tag, but with a forward slash inserted before the tag name
  • 7.
  • 8. HTML Headings HTML headings are defined with the <h1> to <h6> tags. <h1> defines the most important heading. <h6> defines the least important heading: Example <h1>This is heading 1</h1> <h2>This is heading 2</h2> <h3>This is heading 3</h3>
  • 9. HTML Paragraphs HTML paragraphs are defined with the <p> tag: Example <p>This is a paragraph.</p> <p>This is another paragraph.</p>
  • 10. HTML Links HTML links are defined with the <a> tag: Example <a href="https://www.w3schools.com">This is a link</a>
  • 11. HTML Images HTML images are defined with the <img> tag. The source file (src), alternative text (alt), width, and height are provided as attributes: Example <img src=“day01.jpg" alt="W3Schools.com" width="104" height="142">
  • 13. HTML Active Controls HTML Buttons HTML buttons are defined with the <button> tag: Example <button>Click me</button>
  • 14. HTML ListsHTML lists are defined with the <ul> (unordered/bullet list) or the <ol> (ordered/numbered list) tag, followed by <li> tags (list items): Example <ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <ol> <li>Coffee</li> <li>Tea</li> <li>Milk</li>
  • 15. Empty HTML Elements HTML elements with no content are called empty elements. <br> is an empty element without a closing tag (the <br> tag defines a line break): Example <p>This is a <br> paragraph with a line break.</p>
  • 16. HTML Attributes • All HTML elements can have attributes • Attributes provide additional information about an element • Attributes are always specified in the start tag • Attributes usually come in name/value pairs like: name="value“ • <a href="https://www.w3schools.com">This is a link</a> • <img src="img_girl.jpg" width="500" height="600"> • <p style="color:red">This is a paragraph.</p> • <p title="I'm a tooltip"> This is a paragraph. </p> • <p title='John "ShotGun" Nelson'>
  • 18. The HTML Style Attribute Setting the style of an HTML element, can be done with the style attribute. The HTML style attribute has the following syntax: <tagname style="property:value;"> The property is a CSS property. The value is a CSS value.
  • 19. Background Color The CSS background-color property defines the background color for an HTML element. This example sets the background color for a page to powderblue: Example <body style="background-color:powderblue;"> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body>
  • 20. Text Color The CSS color property defines the text color for an HTML element: Example <h1 style="color:blue;">This is a heading</h1> <p style="color:red;">This is a paragraph.</p>
  • 21. Text Size The CSS font-size property defines the text size for an HTML element: Example <h1 style="font-size:300%;">This is a heading</h1> <p style="font-size:160%;">This is a paragraph.</p>
  • 22. Text Alignment The CSS text-align property defines the horizontal text alignment for an HTML element: Example <h1 style="text-align:center;"> Centered Heading</h1> <p style="text-align:center;"> Centered paragraph.</p>
  • 23. In the previous chapter, you learned about the HTML style attribute. HTML also defines special elements for defining text with a special meaning. HTML uses elements like <b> and <i> for formatting output, like bold or italic text. Formatting elements were designed to display special types of text: •<b> - Bold text •<strong> - Important text •<i> - Italic text •<em> - Emphasized text •<mark> - Marked text •<small> - Small text •<del> - Deleted text •<ins> - Inserted text •<sub> - Subscript text •<sup> - Superscript text
  • 24. Quotes, Abbr and Address • <p>Here is a quote from WWF's website:</p> <blockquote cite="http://www.worldwildlife.org/who/index.html"> For 50 years, WWF has been protecting the future of nature. The world's leading conservation organization, WWF works in 100 countries and is supported by 1.2 million members in the United States and close to 5 million globally. </blockquote> • Abbreviation • <p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p> • Address • <address> Written by John Doe.<br> Visit us at:<br> Example.com<br> Box 564, Disneyland<br> USA </address>
  • 27. Background / Foreground Color •Example •<h1 style="background-color:DodgerBlue;">Hello World</h1> <p style="background-color:Tomato;">Lorem ipsum...</p> •Text Color • <h1 style="color:Tomato;">Hello World</h1> <p style="color:DodgerBlue;">Lorem ipsum...</p> <p style="color:MediumSeaGreen;">Ut wisi enim...</p>
  • 28. Border Color • You can set the color of borders: • Hello World • Hello World • Hello World • Example • <h1 style="border:2px solid Tomato;">Hello World</h1> <h1 style="border:2px solid DodgerBlue;">Hello World</h1> <h1 style="border:2px solid Violet;">Hello World</h1>
  • 29.
  • 30.
  • 31.
  • 32.
  • 33. HyperLinks • HTML links are hyperlinks. • You can click on a link and jump to another document. • When you move the mouse over a link, the mouse arrow will turn into a little hand. • Note: A link does not have to be text. It can be an image or any other HTML element. • <a href="url">link text</a> • <a href="html_images.asp">HTML Images</a>
  • 35. Styling HTML with 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. CSS can be added to HTML elements in 3 ways: •Inline - by using the style attribute in HTML elements •Internal - by using a <style> element in the <head> section •External - by using an external CSS file
  • 36. Inline CSS An inline CSS is used to apply a unique style to a single HTML element. An inline CSS uses the style attribute of an HTML element. This example sets the text color of the <h1> element to blue: Example <h1 style="color:blue;">This is a Blue Heading</h1>
  • 37. Internal CSS An internal CSS is used to define a style for a single HTML page. An internal CSS is defined in the <head> section of an HTML page, within a <style> element: Example <!DOCTYPE html> <html> <head> <style> body {background-color: powderblue;} h1 {color: blue;} p {color: red;} </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
  • 38. External CSSAn external style sheet is used to define the style for many HTML pages. With an external style sheet, you can change the look of an entire web site, by changing one file! To use an external style sheet, add a link to it in the <head> section of the HTML page: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body>
  • 39. StyleSheet Attributes •Use the HTML style attribute for inline styling •Use the HTML <style> element to define internal CSS •Use the HTML <link> element to refer to an external CSS file •Use the HTML <head> element to store <style> and <link> elements •Use the CSS color property for text colors •Use the CSS font-family property for text fonts •Use the CSS font-size property for text sizes •Use the CSS border property for borders •Use the CSS padding property for space inside the border •Use the CSS margin property for space outside the border
  • 40. • <style> a:link { color: green; background-color: transparent; text-decoration: none; } a:visited { color: pink; background-color: transparent; text-decoration: none; } a:hover { color: red; background-color: transparent; text-decoration: underline; } a:active { color: yellow; background-color: transparent; text-decoration: underline; } Style for Hyperlink
  • 41. HTML Links - The target Attribute The target attribute specifies where to open the linked document. The target attribute can have one of the following values: •_blank - Opens the linked document in a new window or tab •_self - Opens the linked document in the same window/tab as it was clicked (this is default) •_parent - Opens the linked document in the parent frame •_top - Opens the linked document in the full body of the window •framename - Opens the linked document in a named frame <a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>
  • 43. HTML Images • <!DOCTYPE html> <html> <head> <style> img { width: 100%; } </style> </head> <body> <img src="html5.gif" alt="HTML5 Icon" width="128" height="128"> <img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;"> </body> </html> The width, height, and style attributes are valid in HTML. However, we suggest using the style attribute. It prevents styles sheets from changing the size of images:
  • 44. Image Maps The <map> tag defines an image-map. An image-map is an image with clickable areas. In the image below, click on the computer, the phone, or the cup of coffee: <img src="workplace.jpg" alt="Workplace" usemap="#workmap"> <map name="workmap"> <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm"> <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm"> <area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm"> </map>
  • 46. Table Company Contact Country Alfreds Futterkiste Maria Anders Germany Centro comercial Moctezuma Francisco Chang Mexico Ernst Handel Roland Mendel Austria Island Trading Helen Bennett UK Laughing Bacchus Winecellars Yoshi Tannamuri Canada Magazzini Alimentari Riuniti Giovanni Rovelli Italy
  • 47. Example • <table style="width:100%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table>
  • 48. HTML Table - Adding a Border If you do not specify a border for the table, it will be displayed without borders. A border is set using the CSS border property: Example table, th, td { border: 1px solid black; } table, th, td { border: 1px solid black; border-collapse: collapse; }
  • 49. HTML Table - Left-align Headings By default, table headings are bold and centered. To left-align the table headings, use the CSS text-align prop Example th { text-align: left; }
  • 50. HTML Table - Cells that Span Many Columns To make a cell span more than one column, use the colspan attribute: Example <table style="width:100%"> <tr> <th>Name</th> <th colspan="2">Telephone</th> </tr> <tr> <td>Bill Gates</td> <td>55577854</td> <td>55577855</td> </tr> </table>
  • 51. HTML Table - Cells that Span Many Rows To make a cell span more than one row, use the rowspan attribute: Example <table style="width:100%"> <tr> <th>Name:</th> <td>Bill Gates</td> </tr> <tr> <th rowspan="2">Telephone:</th> <td>55577854</td> </tr> <tr> <td>55577855</td> </tr> </table>
  • 52. HTML Table - Adding a Caption To add a caption to a table, use the <caption> tag: Example <table style="width:100%"> <caption>Monthly savings</caption> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr> <tr> <td>February</td> <td>$50</td> </tr>
  • 53. javaScript • Why Study JavaScript? • JavaScript is one of the 3 languages all web developers must learn: • 1. HTML to define the content of web pages • 2. CSS to specify the layout of web pages • 3. JavaScript to program the behavior of web pages
  • 54. First JavaScript • <!DOCTYPE html> • <html> • <body> • <h2>JavaScript in Body</h2> • <p id="demo"></p> • <script> • document.getElementById("demo").innerHTML = "My First JavaScript"; • </script> • </body>
  • 55. JavaScript Function • <!DOCTYPE html> <html><head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </head> <body> • <h1>A Web Page</h1> <p id="demo">A Paragraph</p> <button type="button" onclick="myFunction()">Try it</button> • </body> </html>
  • 56. JavaScript Can Change HTML Content One of many JavaScript HTML methods is getElementById(). This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript": <!DOCTYPE html> <html> <body> <h2>What Can JavaScript Do?</h2> <p id="demo">JavaScript can change HTML content.</p> <button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button> </body> </html>
  • 57. Light bulb • <!DOCTYPE html> • <html> • <body> • <h2>What Can JavaScript Do?</h2> • <p>JavaScript can change HTML attribute values.</p> • <p>In this case JavaScript changes the value of the src (source) attribute of an image.</p> • <button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button> • <img id="myImage" src="pic_bulboff.gif" style="width:100px"> • <button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button> • </body> • </html>
  • 58. Changing html cstyle • <!DOCTYPE html> • <html> • <body> • <h2>What Can JavaScript Do?</h2> • <p id="demo">JavaScript can change the style of an HTML element.</p> • <button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button> • </body> • </html>
  • 59. Hiding html content • <!DOCTYPE html> • <html> • <body> • <h2>What Can JavaScript Do?</h2> • <p id="demo">JavaScript can hide HTML elements.</p> • <button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button> • </body> • </html>
  • 60. External Call of JavaScript External scripts are practical when the same code is used in many different web pages. JavaScript files have the file extension .js. To use an external script, put the name of the script file in the src (source) attribute of a <script> tag: Example <script src="myScript.js"></script> Try it Yourself » You can place an external script reference in <head> or <body> as you like. The script will behave as if it was located exactly where the <script> tag is located. External scripts cannot contain <script> tags.
  • 61. CODE • <!DOCTYPE html> • <html> • <body> • <h2>External JavaScript</h2> • <p id="demo">A Paragraph.</p> • <button type="button" onclick="myFunction()">Try it</button> • <p>(myFunction is stored in an external file called "myScript.js")</p> • <script src="Script1.js"></script> • </body> // JavaScript source code function myFunction() { document.getElementById("demo").inner HTML = "I am called from external file"; }
  • 62. External JavaScript Advantages • Placing scripts in external files has some advantages: • It separates HTML and code • It makes HTML and JavaScript easier to read and maintain • Cached JavaScript files can speed up page loads • To add several script files to one page - use several script tags:
  • 63. JavaScript Display Possibilities JavaScript can "display" data in different ways: •Writing into an HTML element, using innerHTML. •Writing into the HTML output using document.write() •Writing into an alert box, using window.alert(). •Writing into the browser console, using console.log(
  • 64. 1. Using innerHTML To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content: Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> </body> </html>
  • 65. 2. Document write • <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body> </html>
  • 66. 3. window.alert() • <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> </html>
  • 67. Semicolons ; • Semicolons separate JavaScript statements. • Add a semicolon at the end of each executable statement: • var a, b, c; // Declare 3 variables a = 5; // Assign the value 5 to a b = 6; // Assign the value 6 to b c = a + b; // Assign the sum of a and b to c • When separated by semicolons, multiple statements on one line are allowed: • a = 5; b = 6; c = a + b;
  • 68. • <!DOCTYPE html> • <html> • <body> • <h2>JavaScript Statements</h2> • <p>Multiple statements on one line is allowed.</p> • <p id="demo1"></p> • <script> • var a, b, c; • a = 5; b = 6; c = a + b; • document.getElementById("demo1").innerHTML = c; • </script></body> • </html>
  • 69. Code blocks • <!DOCTYPE html> • <html> • <body> • <h2>JavaScript Statements</h2> • <p>JavaScript code blocks are written between { and }</p> • <button type="button" onclick="myFunction()">Click Me!</button> • <p id="demo1"></p> <p id="demo2"></p> • <script> • function myFunction() { • document.getElementById("demo1").innerHTML = "Hello COMSATS!"; • document.getElementById("demo2").innerHTML = “How are all?"; • } • </script></body> • </html>
  • 70. Keyword Description break Terminates a switch or a loop continue Jumps out of a loop and starts at the top debugger Stops the execution of JavaScript, and calls (if available) the debugging function do ... while Executes a block of statements, and repeats the block, while a condition is true for Marks a block of statements to be executed, as long as a condition is true function Declares a function if ... else Marks a block of statements to be executed, depending on a condition return Exits a function switch Marks a block of statements to be executed, depending on different cases try ... catch Implements error handling to a block of statements var Declares a variable
  • 71. JS Strings • <html> <body> • <h2>JavaScript Strings</h2> • <p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string.</p> • <p id="demo"></p> • <script> • var answer1 = "It's alright"; • var answer2 = "He is called 'Johnny'"; • var answer3 = 'He is called "Johnny"'; • document.getElementById("demo").innerHTML = • answer1 + "<br>" + answer2 + "<br>" + answer3; • document.getElementById("demo").innerHTML = "<br>" + "String length is " + answer3.length; • </script></body> </html>
  • 72. Special Characters The string will be chopped to "We are the so-called ". The solution to avoid this problem, is to use the backslash escape character. The backslash () escape character turns special characters into string characters: Code Result Description ' ' Single quote " " Double quote Backslash <body> <h2>JavaScript Strings</h2> <p>The escape sequence " inserts a double quote in a string.</p> <p id="demo"></p> <script> var x = "We are the so-called "Vikings" from the north."; document.getElementById("demo").innerHTML = x; </script> </body>
  • 73. Strings Can be Objects Normally, JavaScript strings are primitive values, created from literals: var firstName = “xyz"; But strings can also be defined as objects with the keyword new: var firstName = new String(“xyz"); Example var x = “xyz"; var y = new String(“xyz"); // typeof x ?? // typeof y ??
  • 74. String Methods Finding a String in a String The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string: Example var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); Searching for a String in a String The search() method searches a string for a specified value and returns the position of the match: Example var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate"); Extracting String Parts There are 3 methods for extracting a part of a string: •slice(start, end) •substring(start, end) •substr(start, length) •Replace (“old text”,”new text”)
  • 75. String Methods • String.toUpperCase() and String.toLowerCase() • String.Concat() or use + Operator • String.trim() • String.charAt(SomeIndex) • String.charCodeAt(someindex) returns ASCII Code • String[index] or String[index] = ‘x’ • Split () • var txt = "a,b,c,d,e"; // String txt.split(","); // Split on commas txt.split(" "); // Split on spaces txt.split("|");
  • 76. JS Arrays <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p> <p id="demo"></p> <script> var cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Opel"; document.getElementById("demo").innerHTML = cars; </script> </body> </html>
  • 77. Array Elements Can Be Objects • JavaScript variables can be objects. Arrays are special kinds of objects. • Because of this, you can have variables of different types in the same Array. • You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array: • myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars; Array Properties and Methods The real strength of JavaScript arrays are the built-in array properties and methods: Examples var x = cars.length; // The length property returns the number of elements var y = cars.sort(); // The sort() method sorts arrays
  • 78. Looping through Arrays • <body> • <h2>JavaScript Arrays</h2> • <p>The best way to loop through an array is using a standard for loop:</p> • <p id="demo"></p> • <script> • var fruits, text, fLen, i; • fruits = ["Banana", "Orange", "Apple", "Mango"]; • fruits.push("Lemon"); fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits • fLen = fruits.length; • text = "<ul>"; • for (i = 0; i < fLen; i++) { • text += "<li>" + fruits[i] + "</li>"; } • text += "</ul>"; • document.getElementById("demo").innerHTML = text; • </script> • </body>
  • 79. Sorting Arrays • <body> • <h2>JavaScript Array Sort</h2> • <p>Click the buttons to sort the array alphabetically or numerically.</p> • <button onclick="myFunction1()">Sort Alphabetically</button> • <button onclick="myFunction2()">Sort Numerically</button> • <p id="demo"></p> • <script> • var points = [40, 100, 1, 5, 25, 10]; • document.getElementById("demo").innerHTML = points; • function myFunction1() { • points.sort(); • document.getElementById("demo").innerHTML = points; } • function myFunction2() { • points.sort(function (a, b) { return a - b }); • document.getElementById("demo").innerHTML = points; • } </script> </body>
  • 80. JS Dates Date objects are created with the new Date() constructor. There are 4 ways to create a new date object: new Date() new Date(year, month, day, hours, minutes, seconds, mill new Date(milliseconds) new Date(date string)
  • 81. Date methods Method Description getFullYear() Get the year as a four digit number (yyyy) getMonth() Get the month as a number (0-11) getDate() Get the day as a number (1-31) getHours() Get the hour (0-23) getMinutes() Get the minute (0-59) getSeconds() Get the second (0-59) getMilliseconds() Get the millisecond (0-999) getTime() Get the time (milliseconds since January 1, 1970) getDay() Get the weekday as a number (0-6) Date.now() Get the time. ECMAScript 5.
  • 82. Date methods <!DOCTYPE html> <html> <body> <h2>JavaScript getMonth()</h2> <p>The getMonth() method returns the month as a number:</p> <p>You can use an array to display the name of the month:</p> <p id="demo"></p> <script> var d = new Date(); var months = ["January","February","March","April","May","June","July","August","September","October","Novembe r","December"]; document.getElementById("demo").innerHTML = months[d.getMonth()];</script> </body> </html>
  • 83. JavaScript Form Validation • HTML form validation can be done by JavaScript. • If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted: • JavaScript Example • function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == "") { alert("Name must be filled out"); return false; } }
  • 84. Number Validation • <script> • function myFunction() { • var x, text; • // Get the value of the input field with id="numb" • x = document.getElementById("numb").value; • // If x is Not a Number or less than one or greater than 10 • if (isNaN(x) || x < 1 || x > 10) { • text = "Input not valid"; • } else { • text = "Input OK"; • } document.getElementById("demo").innerHTML = text; • } • </script>
  • 85. Constraint Validation HTML Input Attributes Attribute Description disabled Specifies that the input element should be disabled max Specifies the maximum value of an input element min Specifies the minimum value of an input element pattern Specifies the value pattern of an input element required Specifies that the input field requires an element type Specifies the type of an input element
  • 86. Constraint Validation DOM • If an input field contains invalid data, display a message: • The checkValidity() Method • <input id="id1" type="number" min="100" max="300" required> <button onclick="myFunction()">OK</button> <p id="demo"></p> <script> function myFunction() { var inpObj = document.getElementById("id1"); if (!inpObj.checkValidity()) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } } </script> Property Description checkValidity() Returns true if an input element contains valid data. setCustomValidity() Sets the validationMessage property of an input element.
  • 87. JS Animation • D yourself
  • 88. JavaScript vs React.JS • Web apps are becoming increasingly complex and dynamic. In response, new tools and libraries like React have been created to speed up the process. • But how is developing a web app with React different than developing an app with just plain JavaScript?
  • 89. JavaScript • To set some boundaries, let’s first define what we mean by "plain" JavaScript (also called "vanilla" JavaScript). • React is a library that defines the way apps are written. It does this by setting very clear rules about how data can flow through the app, and how the UI will adapt as a result of that changing data. There are other libraries that set similar boundaries, such as Angular and Vue. • Plain JavaScript (that is, JavaScript written without libraries) on the other hand, doesn’t set any rules about how data can be defined, or how the UI can be changed. That makes apps written without these libraries more freeform and customizable. But going this route can also lead to problems down the road
  • 90. The major differences Since there are so many ways to write vanilla JS, it can be difficult to pin down a list of differences that applies to 100% of apps. But here we’ll define some key differences that apply to many plain JS apps that are written without a framework. • How the user interface is first created • How functionality is split up across the app • How data is stored on the browser • How the UI is updated
  • 91. In plain JS, the initial user interface is generally created in HTML on the server. Meaning, HTML is dynamically created on the server, and might look something like this: <div> <h1>Grocery List</h1> <ul> <li>Milk</li> <li>Bread</li> <li>Eggs</li> </ul> </div> That gets sent to the web browser and displayed—no JavaScript needed yet! In contrast, a React app will start with a fixed HTML file that looks like this: <div id=“root”></div> How the user interface is first created
  • 92. UI in REACT Instead of defining the initial UI on the server, the UI gets defined on the browser. So the app starts with a blank container (a div in this case), and then the UI gets loaded into that container. The UI is defined by a component that returns JSX. JSX looks like HTML, but is actually JavaScript - and might look like this: function GroceryList(props) { return ( <div> <h1>Grocery List</h1> <ul> <li>Milk</li> <li>Bread</li> <li>Eggs</li> </ul> </div> ) }; And that new GroceryList component gets mounted (or "rendered") into the div container using a library called ReactDOM: <GroceryList />, <GroceryList />, <GroceryList />, document.getElementById("root") This results in the same initial UI as the plain JS example above except that happens on the browser, instead of beforehand on the server.
  • 93. How functionality is split up across the app With a plain JS app, there are no requirements about how you split up functionality or UI components in an application. For example, our initial grocery list can just be defined in a main index.html file: <div> <h1>Grocery List</h1> <ul id="grocery-list"> <li>Milk</li> <li>Bread</li> <li>Eggs</li> </ul> </div> And the code that updates the list might be buried deep in a separate javascript file: function addItemToList() { // Add item }
  • 94. JS Enforces Different Jscript code to open from all files • React enforces that your app is split into components and that each one of those components maintains all of the code needed to both display and update the UI: function GroceryList(props) { function addItem() { // Add Item } return ( <div> <h1>Grocery List</h1> <ul> <li>Milk</li> <li>Bread</li> <li>Eggs</li> </ul> </div> ) };
  • 95. Main Advantages •This keeps the update code right next to the display code, and makes complicated apps easier to understand. •It also allows for greater code reuse since generic components can be made and shared across an app.
  • 96. Data storage on browser • Once the initial UI is loaded, the user will be able to interact with your app. For interactions like typing into an input box, that text has to be stored somewhere on the browser before it can be used later (to submit to the backend server, for example). • In a plain JS app, that user data is generally stored in the DOM (Document Object Model). • The Document Object Model (DOM) is created and maintained by the browser itself and represents all of the HTML nodes on the entire page. That includes any data stored on those nodes. <input type="text" placeholder="Enter an item" id="item-input" />
  • 97. Change in Value • for just one input change in Jscript not difficult, but it can get tedious for an entire form. Plus if the id of the input changes, you’ll have to make sure to change it in every single spot where you access that id as well. • In contrast, React uses a technique called "controlled components" to set the text value in a JavaScript object as the user types it. • First, a bit of state has to be defined to hold the input value: const [itemInput, setItemInput] = useState("");
  • 98. Input ID change in REACT • And then that set has to be set whenever the input changes. That makes the input box code more complex • <input type="text" placeholder="Enter an item" value={itemInput} onChange={e => setItemInput(e.target.value)}
  • 99. JS Animation • Timer let timer = setInterval(function() { if (animation complete) clearInterval(timer); else increase style.left by 2px}, 20); // change by 2px every 20ms, about 50 frames per second
  • 100. Train Animation let start = Date.now(); // remember start time let timer = setInterval(function() { // how much time passed from the start? Let imePassed = Date.now() - start; if (timePassed >= 2000) { clearInterval(timer); // finish the animation after 2 seconds return; } // draw the animation at the moment timePassed draw(timePassed); }, 20); // as timePassed goes from 0 to 2000 // left gets values from 0px to 400px function draw(timePassed) { train.style.left = timePassed / 5 + 'px'; }
  • 101. Interval Timer setInterval(function() { animate1(); animate2(); animate3(); }, 20) Let’s imagine we have several animations running simultaneously. If we run them separately, then even though each one has setInterval(..., 20), then the browser would have to repaint much more often than every 20ms. That’s because they have different starting time, so “every 20ms” differs between different animations. The intervals are not aligned. So we’ll have several independent runs within 20ms. As Code Shows setInterval(animate1, 20); // independent animations setInterval(animate2, 20); // in different places of the script setInterval(animate3, 20); The better approach is one central timer with one stopwatch
  • 102. Animation when inactive webpages These several independent redraws should be grouped together, to make the redraw easier for the browser and hence load less CPU load and look smoother. There’s one more thing to keep in mind. Sometimes when CPU is overloaded, or there are other reasons to redraw less often (like when the browser tab is hidden), so we really shouldn’t run it every 20ms. But how do we know about that in JavaScript? There’s a specification Animation timing that provides the function requestAnimationFrame. It addresses all these issues and even more. let requestId = requestAnimationFrame(callback) That schedules the callback function to run in the closest time when the browser wants to do animation. If we do changes in elements in callback then they will be grouped together with other requestAnimationFrame callbacks and with CSS animations. So there will be one geometry recalculation and repaint instead of many. The returned value requestId can be used to cancel the call: // cancel the scheduled execution of callback cancelAnimationFrame(requestId);
  • 103. Better Animation Approach <script> let prev = performance.now(); let times = 0; requestAnimationFrame(function measure(time) { document.body.insertAdjacentHTML("beforeEnd", Math.floor(time - prev) + " "); prev = time; if (times++ < 10) requestAnimationFrame(measure); }) </script>
  • 104. Structure Animation Function function animate({timing, draw, duration}) { let start = performance.now(); requestAnimationFrame(function animate(time) { // timeFraction goes from 0 to 1 let timeFraction = (time - start) / duration; if (timeFraction > 1) timeFraction = 1; // calculate the current animation state let progress = timing(timeFraction) draw(progress); // draw it if (timeFraction < 1) { requestAnimationFrame(animate); } } ); }
  • 105. Animate Function • Function animate accepts 3 parameters that essentially describes the animation: • duration • Total time of animation. Like, 1000. • timing(timeFraction) • Timing function, like CSS-property transition-timing-function that gets the fraction of time that passed (0 at start, 1 at the end) and returns the animation completion . • For instance, a linear function means that the animation goes on uniformly with the same speed: function linear(timeFraction) { return timeFraction; }
  • 106. Moving the element draw(progress) The function that takes the animation completion state and draws it. The value progress=0 denotes the beginning animation state, and progress=1 – the end state. This is that function that actually draws out the animation. It can move the element: function draw(progress) { train.style.left = progress + 'px'; }
  • 107. The simple animate Code animate({ duration: 1000, timing(timeFraction) { return timeFraction; }, draw(progress) { elem.style.width = progress * 100 + '%'; } }); // This will call anima
  • 108. Animate function in JS file function animate({duration, draw, timing}) { let start = performance.now(); requestAnimationFrame(function animate(time) { let timeFraction = (time - start) / duration; if (timeFraction > 1) timeFraction = 1; let progress = timing(timeFraction) draw(progress); if (timeFraction < 1) { requestAnimationFrame(animate); } }); }