Javascript
Javascript
Introduction
JavaScript is the most popular programming language in
the world.
We Can do followings things with JavaScript
Change html content
Change html attribute
Change html style
Validate data
Comment
// Change heading
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
JavaScript Variables
JavaScript variables are containers for storing data
values.
Example
var x = 5;
var y = 6;
var z = x + y;
JavaScript Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
JavaScript Assignment Operators
Operator Example
= x=y
+= x += y
-= x -= y
*= x *= y
/= x /= y
%= x %= y
JavaScript String Operators
The + operator can also be used to add (concatenate)
strings.
Example
txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;
JavaScript Comparison and Logical
Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
JavaScript Data Types
JavaScript variables can hold many data types: numbers,
strings, arrays, objects
Example
var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object
The Concept of Data Types
Method Description
toLocaleUpperCase() Converts a string to uppercase letters,
according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a
string
valueOf() Returns the primitive value of a String
object
Special Characters
Code Output
\' single quote
\" double quote
\\ backslash
\n new line
\t tab
\b backspace
Accessing a String as an Array is
Unsafe
This is unsafe and unpredictable:
It does not work in all browsers (not in IE5, IE6, IE7)
It makes strings look like arrays (but they are not)
str[0] = "H" does not give an error (but does not work)
Converting a String to an Array
A string can be converted to an array with the split()
method:
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
JavaScript Numbers
JavaScript Numbers are Always 64-bit Floating Point
Unlike many other programming languages, JavaScript
does not define different types of numbers, like integers,
short, long, floating-point etc.
JavaScript numbers are always stored as double
precision floating point numbers, following the
international IEEE 754 standard.
Lecture 1
JavaScript Objects
JavaScript objects are written with curly braces.
Object properties are written as name:value pairs,
separated by commas.
JavaScript Objects
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Do Not Declare Strings, Numbers, and Booleans as
Objects!
The typeof Operator
You can use the JavaScript typeof operator to find the
type of a JavaScript variable:
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
Undefined
In JavaScript, a variable without a value, has the value
undefined. The typeof is also undefined.
var person; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to
undefined or Null.
var car = "";
var person = null;
Difference
Events Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an
HTML element
onmouseout The user moves the mouse away from
an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the
page
W3Schools JavaScript Reference HTML DOM Events.
Finding HTML Elements
Method Description
document.getElementById() Find an element by
element id
document.getElementsByTagName() Find elements by tag
name
document.getElementsByClassName( Find elements by class
) name
Changing HTML Elements
Method Description
element.innerHTML= Change the inner HTML of an element
element.attribute= Change the attribute of an HTML
element
element.setAttribute(attribute,value) Change the attribute of an HTML
element
element.style.property= Change the style of an HTML element
Using Events
The HTML DOM allows you to execute code when an
event occurs.
Events are generated by the browser when "things
happen" to HTML elements:
An element is clicked on
The page has loaded
Input fields are changed
The addEventListener() method
The addEventListener() method attaches an event handler to the
specified element.
The addEventListener() method attaches an event handler to an element
without overwriting existing event handlers.
You can add many event handlers to one element.
You can add many event handlers of the same type to one element, i.e
two "click" events.
You can add event listeners to any DOM object not only HTML elements.
i.e the window object.
The addEventListener() method makes it easier to control how the event
reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated
from the HTML markup, for better readability and allows you to add event
listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the
removeEventListener() method.
The addEventListener() method
Syntex
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or
"mousedown").
The second parameter is the function we want to call
when the event occurs.
The third parameter is a boolean value specifying whether
to use event bubbling or event capturing. This parameter
is optional.
Adding Events Handlers
Method Description
document.getElementById(id).onclick= Adding event handler code to an
function(){code} onclick event
Event Bubbling or Event Capturing
There are two ways of event propagation in the HTML
DOM, bubbling and capturing.
Event propagation is a way of defining the element order
when an event occurs. If you have a <p> element inside a
<div> element, and the user clicks on the <p> element,
which element's "click" event should be handled first?
In bubbling the inner most element's event is handled first
and then the outer: the <p> element's click event is
handled first, then the <div> element's click event.
Event Bubbling or Event Capturing
In capturing the outer most element's event is handled
first and then the inner: the <div> element's click event will
be handled first, then the <p> element's click event.
With the addEventListener() method you can specify the
propagation type by using the "useCapture" parameter:
addEventListener(event, function, useCapture);
The Browser Object Model
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
The example displays the browser window's height and
width: (NOT including toolbars/scrollbars)
JavaScript Window Screen
The window.screen object can be written without the
window prefix.
Properties:
screen.width
screen.height
screen.availWidth
screen.availHeight
JavaScript Window Screen
document.getElementById("demo").innerHTML =
"Screen Width: " + screen.width;
document.getElementById("demo").innerHTML =
"Available Screen Width: " + screen.availWidth;
The screen.availHeight property returns the height of the
visitor's screen, in pixels, minus interface features like the
Windows Taskbar.
Window Screen Color Depth
document.getElementById("demo").innerHTML =
"Screen Color Depth: " + screen.colorDepth;
Window Location
<script>
document.getElementById("demo").innerHTML =
"Cookies Enabled is " + navigator.cookieEnabled;
</script>
The property product returns the engine name of the
browser:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
navigator.product;
</script>
Warning !!!
<script>
function myFunction() {
alert('Hello');
}
</script>
The setInterval() Method
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML =
d.toLocaleTimeString();
}
Stop the Execution
The clearTimeout() method stops the execution of the
function specified in setTimeout().
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
var myVar = setInterval(myTimer, 1000);
clearInterval(myVar);
JavaScript Cookies