Javascript

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Chapter Five

JavaScript
Introduction
What is JavaScript?
 Is client side scripting language.
 JavaScript was designed to add interactivity to
HTML pages.
 JavaScript is introduced into HTML using
<script> tag in head or body section or
imported form external JS file.
 Everyone can use JavaScript without purchasing
a license.
What can a JavaScript do?
 JavaScript gives HTML designers a programming tool .

 JavaScript can put dynamic text into an HTML page - A


JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a
variable text into an HTML page.

 JavaScript can react to events - A JavaScript can be set to


execute when something
happens, like when a page has finished loading or when a
user clicks on an HTML element
Cont.…..
 JavaScript can be used to validate data.

 JavaScript can be used to detect the visitor's


browser - A JavaScript can be used to detect
the visitor's browse.

 JavaScript can read and write HTML elements -


A JavaScript can read and change the
content of an HTML element.
Introducing JavaScript.
 The HTML <script> tag is used to insert a
JavaScript into an HTML page.
 Example
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
Where to Put JS.
 JavaScript can be put in the body and in the head sections of
an HTML page.
 Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload
event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Cont.…..
 JavaScript can be also placed externally and
imported to a page.
<html>
<head>
<script type="text/javascript" src="abc.js"></script>
</head>
<body>
</body>
</html>
Cont.….
• Output
– JavaScript can "display" data in different ways:
• Writing into an alert box, using window.alert().
• Writing into the HTML output using document.write().
• Writing into an HTML element, using innerHTML.
• Writing into the browser console, using console.log().
JavaScript statements
• JavaScript is a sequence of statements to be
executed by the browser.
• It is case sensitive.
• Comments // single line comment
• /*------------------------*/ multiple line comment
Variables
• Variables are "containers" for storing information.
• Are case sensitive.
• Must begin with a letter or underscore character.
• Reserved words (like JavaScript keywords) cannot
be used as names
• To declare variable use either of the two
statements.
– var variable_name or variable_name
Functions
• Function is a block of code designed to perform a
particular task.
• A function will be executed by an event or by a call to
the function.
• To keep the browser from executing a script when the
page loads, you can put your script into a function.
function functionname(var1,var2,...,varX)
{
some code
}
Conditional Statement
• Conditional statements are used to perform
different actions based on different conditions.
• Variable name=(condition)?value1:value2
• IF ….. Else
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
looping
• Loops execute a block of code a specified
number of times, or while a specified
condition is true.
for (var=startvalue;var<=endvalue;var=var+inc
rement)
{
code to be executed
}
Cont.……
while (var<=endvalue)
{
code to be executed
}

do
{
code to be executed
}
while (var<=endvalue);
Break and Continue
• The break statement will break the loop and
continue executing the code that follows after
the loop (if any).

• The continue statement will break the current


loop and continue with the next value.
Events
• Events are actions that can be detected by JavaScript.
• Events are "things" that happen to HTML elements.
• Event list
– Mouse Events
• Onclick - occurs when the user clicks on an element.
• Ondblclick - occurs when the user double-clicks on an element.
• Onmousedown - occurs when the user presses a mouse button over an
element.
• Onmouseenter - occurs when the pointer is moved onto an element.
• onmouseleave - occurs when the pointer is moved out of an element.
• onmouseover - occurs when the pointer is moved onto an element, or onto
one of its children.
• onmouseup - occurs when a user releases a mouse button over an element.
Cont.….
– Keyboard Events
• Onkeydown - occurs when the user is pressing a key.
• Onkeypress - occurs when the user presses a key.
• Onkeyup - occurs when the user releases a key.
– Form Events
• Onblur - occurs when an element loses focus.
• Onchange - occurs when the content of a form element, the
selection, or the checked state have changed (for <input>,
<select>, and <textarea>)
• Onfocus - occurs when an element gets focus.
• Onreset - occurs when a form is reset.
• Onsubmit - occurs when a form is submitted.
String
• Properties and Methods
– String Length
• The length of a string is found in the built in property length
– concat()
• text1.concat(" ",text2);
– indexOf() – returns the index of the first occurrence of the string.
– lastIndexOf()
– split()
– substr()
– toLowerCase()
– toUpperCase()
– toString()
– search()
Cont.…..
– There are 3 methods for extracting a part of a
string:
• slice(start, end)
• substring(start, end) - cannot accept negative indexes.
• substr(start, length) - the second parameter specifies
the length of the extracted part.
• replace()
– str.replace("Microsoft","W3Schools")

• Special Characters
– \‘, \“, \\, \n, \t
Array
• The Array object is used to store multiple values in a
single variable.
– You Can Have Different Objects in One Array.
• Creating an Array
– Using an array literal
• var array-name = [item1, item2, ...];
– Using the JavaScript Keyword new
• var cars = new Array("Saab", "Volvo", "BMW");
• Accessing the elements
– You refer to an array element by referring to the index
number.
Cont.…..
• Array Properties and Methods
– Length property
• Looping
– For, while
• Methods
– join() method
– It behaves just like toString(), but you can specify the separator.
– fruits.join(" * ")
– Popping and Pushing
– fruits.pop(), fruits.push("Kiwi")
Cont.….
– The shift() method removes the first element of an
array, The unshift() method adds a new element to
an array (at the beginning).
– fruits.shift(), fruits.unshift("Lemon")
– Deleting Elements
– delete fruits[0];
– The sort() method sorts an array alphabetically
– fruits.sort()
– The reverse() method reverses the elements in an
array.
– fruits.reverse();
Cont.……
– The concat() method creates a new array by
concatenating two arrays:
• var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys);
• Reading Assignment On Date.
Dynamic HTML (DHTML)
• DHTML is the art of combining HTML, JavaScript, DOM, and
CSS.
• DHTML is NOT a language or a web standard.
• Dynamic style
– Because the Dynamic HTML (DHTML) Document Object Model (DOM)
makes every HTML element and attribute accessible, it is easy to use
scripts to dynamically read and change styles.

– When the name of the style is more than one word use camel casing
convention.
Cont.……
• Dynamic Content
– With DHTML, you can change the content of the page after it is
loaded.
– It also enables creating, inserting, and deleting elements.
– Changing attribute values.
– Standard DOM Methods
• createElement - Creates a new element (node) of the specified type.
• createTextNode - Creates a plain text node (no HTML).
• appendChild - Adds the node to the parent element as the last child.
• insertBefore - Inserts the node into the document as a child node of the parent.
– var newItem = document.createElement("LI") // Create a <li> node
var textnode = document.createTextNode("Water") // Create a text node
newItem.appendChild(textnode) // Append the text to <li>
var list = document.getElementById("myList") // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]);
• replaceChild - Replaces an existing child element with a new child element.
Cont.…..
• Timing Events
– With JavaScript, it is possible to execute some code at
specified time-intervals. This is called timing events
– The two key methods that are used are:
• setInterval() - executes a function, over and over again, at
specified time intervals
– myVar = window.setInterval("javascript function", milliseconds);
– There are 1000 milliseconds in one second
– window.clearInterval(intervalVariable)
• setTimeout() - executes a function, once, after waiting a
specified number of milliseconds
– myVar = window.setTimeout("javascript function", milliseconds);

You might also like