Sunteți pe pagina 1din 35

INTRODUCTION TO

JAVASCRIPT
1 TECHNINZAZ
CONFIDENTIAL
P R O G RA M AGE NDA

1 What is JavaScript?
2
Operators, Functions, Objects & JSON
3
DOM & Events
4
jQuery & Ajax

TECHNINZAZ
CONFIDENTIAL
SECTION 1:

WHAT IS
JAVASCRIPT?
TECHNINZAZ
CONFIDENTIAL
J AVA S C R I P T

 JavaScript is a cross-platform, object-oriented scripting language


 JavaScript is a full-fledged dynamic programming language that
can provide dynamic interactivity on websites.
 JavaScript is very easy to implement because it is integrated with
HTML
 JavaScript cannot run independently. It has to be included inside an
HTML page
 JavaScript can be used on Client’s side and server side
 JavaScript is case sensitive

TECHNINZAZ
CONFIDENTIAL
J AVA S C R I P T i n H T M L
Any number of scripts can be inserted in an HTML page
Scripts can be placed in the HEAD or in the BODY
• In the HEAD, scripts are run before the page is displayed
• In the BODY, scripts are run as the page is displayed
JavaScript can be inserted into documents by using the SCRIPT tag in 2 ways
Internal Script – Scripts that are written an the HTML page
• Eg : <script type="text/javascript“> alert("Hello World!");<script>
 External Script - Scripts can also be loaded from an external JavaScript file. This is
used for the purpose of reusability.
• Eg: <script src="myscript.js"></script>
Inline Script – Scripts added at HTML element level
• Eg: <button onclick="document.getElementById('demo').innerHTML=Date()">The
time is?</button> TECHNINZAZ
CONFIDENTIAL
J a v a S c r i p t Fi l e E x a m p l e
 JavaScript file has “.js” extension
 Both the codes below(Internal script & External Script) lead the same output

sample.js
alert(‘Hello world!!’);

sample.html
<html>
<body>
<script src=“sample.js” type=“text/javascript”/>
</body>
</html>

sample.html
<html>
<body>
<script>
alert(‘Hello world!!’);
</script>
</body>
</html>

TECHNINZAZ
CONFIDENTIAL
JavaScript Debugging
JavaScript code might contain syntax errors, or logical errors, that are difficult to
diagnose. Often, when JavaScript code contains errors, nothing will happen. There
are no error messages, and you will get no indications where to search for errors.
In order to identify the errors we use
obrowser’s built-in-debugger
oconsole.log() can be used to display values in the debugger
oIn the debugger window, you can set breakpoints when JavaScript will stop
executing, and let you examine JavaScript values
oThe debugger keyword stops the execution of JavaScript. This has the same
function as setting a breakpoint in the debugger.

TECHNINZAZ
CONFIDENTIAL
JavaScript Comments
 JavaScript comments can be used to explain JavaScript code, and to make it
more readable.
 Using comments to prevent execution of code is suitable for code testing.
 Single Line Comments used to comment one line at a time –
Eg. //var x = 5 + 3;
 Multi-line Comments used to comment any text between /* and */ which will be
ignored by JavaScript.
Eg: /* var x = 5 + 3; alert(‘x = ‘+x);*/

TECHNINZAZ
CONFIDENTIAL
SECTION 2:

OPERATORS,
FUNCTIONS,
OBJECTS & TECHNINZAZ
CONFIDENTIAL
J a v a S c r i p t Va r i a b l e s
JavaScript variables are containers for storing data values.
JavaScript has variables that you can declare with the optional var keyword
Variables declared within a function are local to that function
Variables declared outside of any function are global variables
Ex: var x = 5; where x is a variable with value 5
Based on the value assigned to the variable the data type will change
oEx: var x = 5; // here x is a number
ovar x=“Hello”; //here x is a String
ovar x= true; // here x is a boolean

TECHNINZAZ
CONFIDENTIAL
JavaScript Operators
JavaScript Operators are used to perform different operations like
Arithmetic Operators - Arithmetic operations on variables
Ex: x=5; y=10 ; z=(x+y)-(y-x); Output – 10
Assignment Operators - assign values to variables
Ex: var x=5; var y+=x; Output – 6
String Operators – string operations on variables
Ex: var x=“Hello”; var y=“World!!” ; var z= x+y; Ouput – Hello World!!
Comparison Operators – Comparison operators are used in logical statements to
determine equality or difference between variables or values.
Ex: var x=5; x === 5 will lead to true
Logical Operators- Logical operators are used to determine the logic between
variables or values. TECHNINZAZ
Ex : var x = 6 ;var y = 3; x>10 && y<4 will lead to false CONFIDENTIAL
JavaScript Arrays
An array is a special variable, which can hold more than one value at a time.
An array can be accessed by referring to an index number.
Ex: var fruits= [“Tomato", “Onion", “Carrot"];

sample.html
<html>
<body >
<span id="fruits"></span>
<div id="first"></div>
<script>
var fruits= ["Tomato", "Onion", "Carrot"];
document.getElementById('fruits').innerHTML
= fruits;
document.getElementById('first').innerHTML
= fruits[0];
</script>
</body>
</html> TECHNINZAZ
CONFIDENTIAL
J a v a S c r i p t Fu n c t i o n s
A JavaScript function is a block of code designed to perform a particular task.
JavaScript lets you define functions using the function keyword.
Ex : function name(arg1,arg2,….argn){ //Code to be executed }
When JavaScript reaches a return statement, the function will stop executing
and value is "returned" back to the "caller".
sample.html
<html>
<body onload="onLoadMethod()">
<span id="simple"></span>
<script>
function onLoadMethod(){

document.getElementById("simple").innerHTML="
Hello World!!";
}
</script>
</body>
</html> TECHNINZAZ
CONFIDENTIAL
JavaScript Objects
JavaScript is object-oriented language. sample.html
<html>
There are 3 ways to create objects. <body >
<script>
oBy object literal – object has property value var emp={id:102,name:"Shyam
pairs separated by : Kumar",salary:40000};
oBy creating instance of Object directly var empobj = new Object();
empobj.id=101; empobj.name="Varun
(using new keyword) Sharma"; empobj.salary= 50000;
oBy using an object constructor (using new function empFunc(id,name,salary){
this.id=id;
keyword) this.name=name;
this.salary=salary;
}
e=new empFunc(103,"Vimal
Jaiswal",30000);
console.log(emp.id + ' '+empobj.id+'
'+e.id);
</script> TECHNINZAZ
CONFIDENTIAL
</body>
Built – In JavaScript Objects
In JavaScript, almost "everything" is an object.
Some basic objects that are built-in JavaScript objects are:
 String
 Number
 Date
 Array
 Boolean
 Math

TECHNINZAZ
CONFIDENTIAL
JSON

JSON stands for JavaScript Object Notation


JSON consists of key/value pairs similar to JavaScript Object.
JSON Keys must be strings, and values must be a valid JSON data type. Keys and
values are separated by a colon. Each key/value pair is separated by a comma.
JSON is lightweight data interchange format which is often used to exchange
data between server to client.
Any Text and be converted to JSON and any JSON can be converted to text easily

TECHNINZAZ
CONFIDENTIAL
J S O N D a t a Ty p e s
In JSON, values must be one of the following data types:
String Example
Number <script>
var string =
Object (JSON object) { "name":"John" }
Array var num = { "age":30 } ;
var json = { "employee":
Boolean { "name":"John", "age":30,
city":"New York" }} ;
null
var array = { "employees":
[ "John", "Anna", "Peter" ]};
var Boolean = { "sale":true }
var empty = {“empty“:null } ;
</script> TECHNINZAZ
CONFIDENTIAL
JSON Objects

Following are the operations that can be performed on JSON


Objects
Access Object Values – Object Example
Values can be accessed using a (.) notation
or ([]) notation <script>
var myObj =
Modify Object Values
{ "name":"John", "age":30, "car":null };
Delete Object Properties console.log(myObj.name);
console.log(myObj[“name”]);
myObj.name = “Ram”;
console.log(myObj.name);
delete myObj.car;
console.log(myObj.car);
</script>
TECHNINZAZ
CONFIDENTIAL
JSON Methods

Following are some of the JSON built in functions:


JSON.parse() - Converts text into a JavaScript object
JSON.stringify() – Converts JSON object to text

Example
<script>
var myObj = { "name":"John",
"age":30, "car":null };
var myJSON = JSON.stringify(myObj);
console.log(myJSON);
var obj = JSON.parse('{ "name":"John",
"age":30, "city":"New York"}');
console.log(obj.name);
</script>

TECHNINZAZ
CONFIDENTIAL
SECTION 3:

DOM &
EVENTS
TECHNINZAZ
CONFIDENTIAL
DOM (DOCUMENT OBJECT MODEL
When a web page is loaded, the browser creates a Document Object Model of the page
The HTML DOM model is constructed as a tree of Objects
The HTML DOM is a standard object model and programming interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

TECHNINZAZ
CONFIDENTIAL
HTML DOM DOCUMENT OBJECT

The document object represents your web page.


The HTML DOM document object is the owner of all other objects in
your web page.
You can always start with accessing the document object to
oAccess any element in an HTML page
oChange HTML Elements
oAdding and Deleting Elements
oEvent Handlers
oFinding HTML Objects

TECHNINZAZ
CONFIDENTIAL
Sample.html
<!DOCTYPE html>
<html>
<body>
Fi n d i n g H T M L E l e m e n t s <p id="intro">Hello World!</p>
<p class="second">This example
demonstrates the <b>getElementById</b>
In order to manipulate HTML elements we method!</p>
need to find the elements first. <p id="demo"></p>
<span>Hello Span Text here</span>
Different ways to find the elements: <script>
var myElement =
• getElementById(id) – selects the element document.getElementById("intro");
with id
document.getElementById("demo").innerHTM
• getElementsByTagName(tag) – selects the L=
element by tag "The text from the intro paragraph is " +
• getElementsByClassName(class) – selects myElement.innerHTML;
var y =
element by classname document.getElementsByClassName("second
• document.querySelectorAll(‘selector’) – ")[0].style.display='none';
var x =
selects element by selector
document.getElementsByTagName("p")
[2].style.background='yellow';
document.querySelector('p+span').style.font
Weight='bold'; TECHNINZAZ
</script> </body> </html> CONFIDENTIAL
Changing HTML Elements Sample.html
<!DOCTYPE html>
<html>
<body>
JavaScript can create dynamic HTML content. <p id="p1">Hello World!</p>
Different ways to modify elements: <div>
<img id="myImage"
• document.write() – writes directly to the html src="smiley.gif"></div>
page <script>
• innerHTML – changes the content of an HTML document.write(Date());
element document.getElementById("p1").innerH
• getElementById(id).attribute – change the value TML = "New text!";
document.getElementById("myImage")
of an HTML element’s attribute
.src =
"../html/education_learning_original.pn
g";
</script>
</body>
</html>
TECHNINZAZ
CONFIDENTIAL
Changing HTML Style
Sample.html
The HTML DOM allows JavaScript to change <!DOCTYPE html>
the style of HTML elements. <html>
<body>
document.getElementById(id).style.property <p id="intro">Hello World!</p>
=new style changes the css style of the <p id="demo">Welcome to
element with id. training</p>
<script>
var myElement =
document.getElementById("intro").styl
e.color='blue';
document.getElementById("demo").styl
e.background = "#efefef";
</script>
</body>
</html>
TECHNINZAZ
CONFIDENTIAL
J AVA S C R I P T E V E N T S
 JavaScript's interaction with HTML is handled through events
that occur when the user or the browser manipulates a page.
 When an event occurs, user can handle the event by simply
executing a piece of JavaScript code
 Different JavaScript Events are
 Click Events – event fired on click of an element
 Load Events – event fired on load of the element
 Input Events – event fired upon entering value in an input element
 Mouse Events – events fired upon mouse actions
 Others

TECHNINZAZ
CONFIDENTIAL
J A V A S C R I PcanT beBused
JavaScript r otowaccess
s e randOmanipulate
b j e c tthe
s Browser
a n dobjects
Alerts
 There are different Browser Objects. They are:
o Window Object - Open , close move browser window. Retrieve
height and width of browser’s view port
o Screen Object – Retrieve user’s screen properties like height, width
etc
o Location Object – Retrieve current page url, host, port etc also
redirect to another page
o History Object – Retrieve browsers history like back and forward
o Navigator Object - Retrieve information about visitor's browser like
version, platform, user-agent etc
o Cookies – Retrieve information about the cookies stored in the
browser
o Popup Boxes – Alerts that flash on the screen

TECHNINZAZ
CONFIDENTIAL
SECTION 4:

JQUERY AND
AJAX
TECHNINZAZ
CONFIDENTIAL
jQuery
jQuery is a lightweight JavaScript Library
jQuery simplifies lot of the complicated things from JavaScript, like HTML
document traversing, event handling, animating, and Ajax interactions for Rapid
Web Development
jQuery can be used by simply downloading the library and including the js file
within script tag or simply refer to the source location of the library.
 Eg : <script type = "text/javascript" src = "/jquery/jquery-
2.1.3.min.js"></script>
 <script type="text/javascript" src =
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js” ></script>
The jQuery syntax is tailor-made for selecting HTML elements and performing
some action on the element(s). Basic syntax is: $(selector).action()
 Eg : $("p").hide() hides all the paragraph element in the document. Here $TECHNINZAZ
sign
CONFIDENTIAL
is to access jQuery. “p” is to find all paragraph elements in the document. hide()
Element Selectors Example:

<script>
jQuery selectors are used to select $(document).ready( function(){
$('span').hide();
the exact element in HTML $('#pid').attr("style","color:blue");
$('.pcls').css("background-color","yellow");
document. Following are few ways of $
selecting an element: ('a[href^="http://www.oracle"]').attr("style","colo
r:tomato");
• Tag Name- Selects all elements });</script>
<body>
which match with the tag name. <span>Hello World</span>
<p id="pid">This is a Paragraph</p>
• ID - Selects a single element which <p class="pcls">This is another
paragraph</p>
matches with the given ID. <a
href="http://www.oracle.com">Oracle</a><br>
• Class - Selects all elements which <a
match with the given Class. href="http://www.google.com">Google</a>
</body>
• Query - Selects all elements based
on the query. TECHNINZAZ
CONFIDENTIAL
Manipulation Of Elements
jQuery allows manipulation of an html element. Following are few ways of manipulating an
element:
• .html() – Get or set the HTML contents of an element
• .height() & .width()– Get or set the height/ weight of an element
• .val() – Get or set the value of and element
• .attr() – This is an attribute manipulate which manipulates the attributes of an element
• .insertAfter() – places the selected element(s) after the element provided as an argument
• .insertBefore() – places the selected element(s) before the element provided as an argument
• .appendTo() – places the selected element(s) at the end of the element(inside the element)
• .prependTo() – places the selected element(s) at the start of the element(inside the element)
• .remove() – removes the selected element

TECHNINZAZ
CONFIDENTIAL
Tr a v e r s i n g
jQuery traversing means moving through the dom structure in order to find
the element based on its relation with other elements.
There are few methods for traversing the dom they are:
• .parent() – finds the immediate parent of the selected element
• .parents() – finds the parent(s) of the selected element
• .children() – finds the immediate child element(s) of the selected element.
• .find() – finds the child element(s) of the selected element
• .next() – finds the next element of the selected element
• .prev() – finds the previous element of the selected element
• .siblings() – finds the sibling(s) of the selected element

TECHNINZAZ
CONFIDENTIAL
EFFECTS

jQuery makes it trivial to add simple effects to your page.


Effects can use the built-in settings, or provide a customized duration.
Here are few most commonly used effects:
 .show() & .hide() – used to show and hide the selected elements
 .toggle() – used to switch between hide and show based on current state.
 . animate({params},speed, callback) – used to create custom animations
where params define the CSS properties, speed in milliseconds, callback
function after animation is complete

TECHNINZAZ
CONFIDENTIAL
EVENTS

jQuery helps in setting up event driven responses.


Events are often triggered based on user’s interaction with the elements.
Here are few most commonly used events:
• .ready() – event is fired when the page is loaded
• .click() – event is fired when the selected element is clicked

TECHNINZAZ
CONFIDENTIAL
AJAX Example
<script>
$(document).ready(function(){
$("button").click(function(){
AJAX stands for Asynchronous $.ajax({url: "demo_test.txt",
JavaScript and XML is the art of dataType: 'text'
success:
exchanging data with a server, and function(result){
update parts of a web page. $("#div1").html(result);
}});
Request/Receive data from a });
server without reloading the entire });
</script>
page. <body>
Syntax - $.ajax({name:value, <div id="div1"> Change This
Text</h2></div>
name:value, ... }) <button>Get External
Content</button>
</body>
TECHNINZAZ
CONFIDENTIAL

S-ar putea să vă placă și