JavaScript is a client-side scripting language that allows web pages to become interactive and dynamic. It can update and modify the content of an HTML page without needing to reload the page. JavaScript code can be embedded directly in HTML pages or placed in separate .js files. Common uses of JavaScript include validating form input, detecting the visitor's browser, creating cookies, and adding interactivity to HTML elements like buttons and links.
Introduction to JavaScript by Kaushal Kishore, OSSCube LLC.
JavaScript origins, definitions as a lightweight, interpreted language and its differences from Java.
Primitive data types in JavaScript, variables creation, naming conventions, and comment styles.
Overview of JavaScript arithmetic, comparison, logical, and special operators.
Conditional statements (if, switch) and looping structures (while, for) in JavaScript.
Creating and manipulating arrays and objects, including properties, length, and methods.Using the DOM to access and manipulate HTML elements, document structure, and methods.
Event object usage for handling mouse events, key presses, and event types.
Final remarks and additional resources for more information on JavaScript.
Building Web Sites:Introduction to JavaScript Kaushal Kishore Software Engineer OSSCube LLC [email_address] www.adhouraacademy.com
2.
What is JavaScriptJavaScript was originally developed by Brendan Eich of Netscape under the name Mocha , which was later renamed to LiveScript , and finally to JavaScript A lightweight programming language that runs in a Web browser JavaScript is a Client Side Scripting Language. Also known as ECMAScript Interpreted, not compiled. JavaScript Syntax are similar to C and Java Language. JavaScript code is usually embedded directly into HTML pages JavaScript is reasonably platform-independent
3.
What Can JavaScriptDo? JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate input data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies
4.
When not touse JavaScript When you need to access other resources. Files Programs Databases When you are using sensitive or copyrighted data or algorithms. Your JavaScript code is open to the public .
5.
JavaScript is notJava Java and JavaScript are two completely different languages in both concept and design! JavaScript has some features that resemble features in Java: JavaScript has Objects and primitive data types JavaScript has qualified names; for example, document.write("Hello World"); JavaScript has Events and event handlers Exception handling in JavaScript is almost the same as in Java JavaScript has some features unlike anything in Java: Variable names are untyped: the type of a variable depends on the value it is currently holding Objects and arrays are defined in quite a different way JavaScript is an interpreted language but java is both interpreted and compiled
6.
Where Do YouPlace Scripts? JavaScript can be put in the <head> or in the <body> of an HTML document JavaScript functions should be defined in the <head> This ensures that the function is loaded before it is needed JavaScript in the <body> will be executed as the page loads JavaScript can be put in a separate .js file <script src="myJavaScriptFile.js"></script> Put this HTML wherever you would put the actual JavaScript code An external .js file lets you use the same JavaScript on multiple HTML pages The external .js file cannot itself contain a <script> tag JavaScript can be put in HTML form object, such as a button This JavaScript will be executed when the form object is used
7.
Referencing External JavaScriptFile Scripts can be provided locally or remotely accessible JavaScript file using src attribute <html> <head> <script language="JavaScript“ type="text/javascript“ src="http://somesite/myOwnJavaScript.js"> </script> <script language="JavaScript“ type="text/javascript“ src="myOwnSubdirectory/myOwn2ndJavaScript.js"> </script>
8.
Primitive Datatypes JavaScripthas three “primitive” types: number , string , and boolean Numbers are always stored as floating-point values Hexadecimal numbers begin with 0x Some platforms treat 0123 as octal, others treat it as decimal Strings may be enclosed in single quotes or double quotes Strings can contains \n (newline), \" (double quote), etc. Booleans are either true or false 0 , "0", empty strings, undefined , null , and NaN are false , other values are true
9.
JavaScript Variable Youcreate a variable with or without the “var” statement var num = “1”; var name = “Kaushal”; var phone = “123-456-7890”; Variables names must begin with a letter or underscore Variable names are case-sensitive Variables are untyped (they can hold values of any type) The word var is optional (but it’s good style to use it) Variables declared within a function are local to that function (accessible only within that function) Variables declared outside a function are global (accessible from anywhere on the page)
10.
Comments Comments areas in C or Java: Single Line Comment // Paragraph Comment /*….*/ Java’s javadoc comments, /** ... */, are treated just the same as /* ... */ comments ; they have no special meaning in JavaScript
11.
Operators of JavaScript1 Because most JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it Arithmetic operators: + - * / % ++ -- Comparison operators: < <= == != >= > Logical operators: && || ! (&& and || are short-circuit operators) Bitwise operators: & | ^ ~ << >> >>> Assignment operators: += -= *= /= %= <<= >>= >>>= &= ^= |=
12.
Operators of JavaScript2 String operator: + The conditional operator: condition ? value_if_true : value_if_false Special equality tests: == and != try to convert their operands to the same type before performing the test === and !== consider their operands unequal if they are of different types Additional operators (to be discussed): new typeof void delete
13.
JavaScript Conditional StatementsIn JavaScript we have the following conditional statements: if statement if...else statement if...else if....else statement s witch statement
14.
JavaScript Looping Statementwhile Syntax: while ( condition ) { code to be executed } d o...while Syntax: do { code to be executed } while ( condition ) For Syntax: for ( initialization ; condition ; increment ) { code to be executed } For…in Syntax: for ( variable in object ) { code to be executed }
15.
Example of for..inStatement <html> <body> <script> var person={fname:"John",lname:"Doe",age:25}; for (x in person) { document.write(person[x] + " "); } </script> </body> </html>
16.
Array Literals Youdon’t declare the types of variables in JavaScript JavaScript has array literals, written with brackets and commas Example: color = ["red", "yellow", "green", "blue"]; Arrays are zero-based: color[0] is "red" If you put two commas in a row, the array has an “empty” element in that location Example: color = ["red", , , "green", "blue"]; color has 5 elements However, a single comma at the end is ignored Example: color = ["red", , , "green", "blue”,]; still has 5 elements
17.
Four ways tocreate an Array You can use an array literal: var colors = ["red", "green", "blue"]; You can use new Array() to create an empty array: var colors = new Array(); You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; You can use new Array(n) with a single numeric argument to create an array of that size var colors = new Array(3); You can use new Array(…) with two or more arguments to create an array containing those values: var colors = new Array("red","green", "blue");
18.
The length ofan array If myArray is an array, its length is given by myArray.length Array length can be changed by assignment beyond the current length Example: var myArray = new Array(5); myArray[10] = 3; Arrays are sparse, that is, space is only allocated for elements that have been assigned a value Example: myArray[50000] = 3; is perfectly OK But indices must be between 0 and 2 32 -1 As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]
19.
Arrays and objectsArrays are objects car = { myCar: "Saturn", 7: "Mazda" } car[7] is the same as car.7 car.myCar is the same as car["myCar"] If you know the name of a property, you can use dot notation: car.myCar If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car.["my" + "Car"]
20.
Array functions IfmyArray is an array, myArray.sort() sorts the array alphabetically myArray.reverse() reverses the array elements myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length myArray.pop() removes and returns the last element of the array, and decrements the array’s length myArray.toString() returns a string containing the values of the array elements, separated by commas
21.
Exception Handling 1Exception handling in JavaScript is almost the same as in Java throw expression creates and throws an exception The expression is the value of the exception, and can be of any type (often, it's a literal String) try { statements to try } catch (e) { // Notice: no type declaration for e exception-handling statements } finally { // optional, as usual code that is always executed } With this form, there is only one catch clause
22.
Exception Handling 2try { statements to try } catch (e if test1) { exception-handling for the case that test1 is true } catch (e if test2) { exception-handling for when test1 is false and test2 is true } catch (e) { exception-handling for when both test1and test2 are false } finally { // optional, as usual code that is always executed } Typically, the test would be something like e == "InvalidNameException"
23.
JavaScript Popup BoxesAlert box User will have to click "OK" to proceed alert("sometext") Confirm box User will have to click either "OK" or "Cancel" to proceed confirm("sometext") Prompt box User will have to click either "OK" or "Cancel" to proceed after entering an input value prompt("sometext","defaultvalue")
24.
JavaScript Functions JavaScriptfunctions are created by the help of “function” keyword. Syntax: function function_name(arguments) {statement here} A JavaScript function contains some code that will be executed only by an event or by a call to that function To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file). Functions can be defined either <head> or <body> section. As a convention, they are typically defined in the <head> section
Events & EventHandlers Every element on a web page has certain events which can trigger invocation of event handlers Attributes are inserted into HTML tags to define events and event handlers Examples of events A mouse click A web page or an image loading Mouse over a hot spot on the web page Selecting an input box in an HTML form Submitting an HTML form A keystroke
27.
Events onabort -Loading of an image is interrupted onblur - An element loses focus onchange - The content of a field changes onclick - Mouse clicks an object ondblclick - Mouse double-clicks an object onerror - An error occurs when loading a document or an image onfocus - An element gets focus onkeydown - A keyboard key is pressed onkeypress - A keyboard key is pressed or held down onkeyup - A keyboard key is released onload - A page or an image is finished loading onmousedown - A mouse button is pressed onmousemove - The mouse is moved
28.
Events onmouseout -The mouse is moved off an element onmouseover - The mouse is moved over an element onmouseup - A mouse button is released onreset - The reset button is clicked onresize - A window or frame is resized onselect - Text is selected onsubmit - The submit button is clicked onunload - The user exits the page
29.
onSubmit The onSubmit event is used to validate all form fields before submitting it. Example: The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be canceled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.html“ onsubmit="return checkForm() ">
30.
Example & Demo:onSubmit <html> <head> <script type="text/javascript"> function validate() { // return true or false based on validation logic } </script> </head> <body> <form action="tryjs_submitpage.htm" onsubmit="return validate()"> Name (max 10 chararcters): <input type="text" id="fname" size="20"><br /> Age (from 1 to 100): <input type="text" id="age" size="20"><br /> E-mail: <input type="text" id="email" size="20"><br /> <br /> <input type="submit" value="Submit"> </form> </body> </html>
31.
Example & Demo:onblur <html> <head> <script type="text/javascript"> function upperCase() { var x=document.getElementById("fname").value document.getElementById("fname").value=x.toUpperCase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="upperCase()"> </body> </html>
32.
JavaScript Object JavaScriptis an Object Oriented Programming (OOP) language A JavaScript object has properties and methods Example: String JavaScript object has length property and toUpperCase() method <script type="text/javascript"> var txt="Hello World!" document.write(txt.length) document.write(txt.toUpperCase()) </script>
33.
JavaScript Built-in ObjectsArray object Boolean object Date object Math object Number object String object Window object Navigator object Screen object History object Location object
34.
Creating Your OwnJavaScript Objects 3 different ways Create a direct instance of an object by using built-in constructor for the Object class Create a template (Constructor) first and then create an instance of an object from it Create object instance as Hash Literal
35.
Option 1: Creatinga Direct Instance of a JavaScript Object By invoking the built-in constructor for the Object class personObj=new Object(); // Initially empty with no properties or methods Add properties to it personObj.firstname="John"; personObj.age=50; Add an anonymous function to the personObj personObj.tellYourage=function(){ alert(“This age is ” + this.age); } // You can call then tellYourage function as following personObj.tellYourage();
36.
Option 1:Creating aDirect Instance of a JavaScript Object Add a pre-defined function function tellYourage(){ alert(“The age is” + this.age); } personObj.tellYourage=tellYourage; Note that the following two lines of code are doing completely different things // Set property with a function personObj.tellYourage=tellYourage; // Set property with returned value of the function personObj.tellYourage=tellYourage();
37.
Option 2: Creatinga template of a JavaScript Object The template defines the structure of a JavaScript object in the form of a function You can think of the template as a constructor function Person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.tellYourage=function(){ alert(“This age is ” + this.age); } }
38.
Option 2: Creatinga template of a JavaScript Object Once you have the template, you can create new instances of the object myFather=new Person("John","Doe",50,"blue"); myMother=new Person("Sally","Rally",48,"green"); You can add new properties and functions to new objects myFather.newField = “some data”; myFather.myfunction = function() { alert(this["fullName"] + ” is ” + this.age); }
39.
Option 3: CreatingJavaScript Object as a Hash Literal Create personObj JavaScript object var personObj = { firstname: "John", lastname: "Doe", age: 50, tellYourage: function () { alert(“The age is ” + this.age ); } tellSomething: function(something) { alert(something); } } personObj.tellYourage(); personObj.tellSomething(“Life is good!”);
40.
HTML DOM TheHTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents All HTML elements, along with their containing text and attributes, can be accessed through the DOM. The contents can be modified or deleted, and new elements can be created. JavaScript uses the HTML Document Object Model to manipulate HTML. Levels of the DOM are dot-separated in the syntax.
41.
HTML DOM ObjectsAnchor object Document object Event object Form and Form Input object Frame, Frameset, and IFrame objects Image object Location object Navigator object Option and Select objects Screen object Table, TableHeader, TableRow, TableData objects Window object
Document Object: Writetext to the output <html> <body> <script type="text/javascript"> document.write(“<h1>Hello World!</h1>") </script> </body> </html>
44.
Document Object: UsegetElementById() <html> <head> <script type="text/javascript"> function getElement() { var x=document.getElementById("myHeader") alert("I am a " + x.tagName + " element") } </script> </head> <body> <h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1> </body> </html>
45.
Document Object: UsegetElementsByName() <html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByName("myInput") alert(x.length + " elements!") } </script> </head> <body> <input name="myInput" type="text" size="20"><br /> <input name="myInput" type="text" size="20"><br /> <input name="myInput" type="text" size="20"><br /> <br /> <input type="button" onclick="getElements()" value="How many elements named 'myInput'?"> </body> </html>
46.
Return the innerHTMLof the first anchor in a document <html> <body> <a name="first">First anchor</a><br /> <a name="second">Second anchor</a><br /> <a name="third">Third anchor</a><br /> <br /> InnerHTML of the first anchor in this document: <script type="text/javascript"> document.write(document.anchors[0].innerHTML) </script> </body> </html>
47.
Event Object: Whatare the coordinates of the cursor? <html> <head> <script type="text/javascript"> function show_coords(event) { x=event.clientX y=event.clientY alert("X coords: " + x + ", Y coords: " + y) } </script> </head> <body onmousedown="show_coords(event)"> <p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p> </body> </html>
48.
Event Object: Whatis the unicode of the key pressed? <html> <head> <script type="text/javascript"> function whichButton(event) { alert(event.keyCode) } </script> </head> <body onkeyup="whichButton(event)"> <p><b>Note:</b> Make sure the right frame has focus when trying this example!</p> <p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p> </body> </html>
49.
Event Object: Whichevent type occurred? <html> <head> <script type="text/javascript"> function whichType(event) { alert(event.type) } </script> </head> <body onmousedown="whichType(event)"> <p> Click on the document. An alert box will alert which type of event occurred. </p> </body> </html>