Sie sind auf Seite 1von 39

JavaScript

What is a JavaScript?
object-oriented scripting language for creating
dynamic online applications.
usually embedded directly into HTML pages.
lightweight programming language.
an interpreted language.
designed to add interactivity to HTML pages.
Everyone can use JavaScript without purchasing a
license.
What can a JavaScript Do?
react to events
used to validate data
used to create cookies
read and write HTML elements
used to detect the visitor's browser
put dynamic text into an HTML page
Sample JavaScript
<html>
<head>
<title>JavaScript</title>
</head>

<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>

</html>

JavaScript Statements
sequence of statements to be executed by the
browser
JavaScript is Case Sensitive
JS statements are ended with semicolon (;) but
optional
Where to Put the JavaScript?
1. Scripts in the head section
2. Scripts in the body section
3. Scripts in both the body and the head section
4. Scripts using an External JavaScript
Scripts in the head section
<html>
<head>
<script type="text/javascript">
function message() {
document.write("Hello!");
}
</script>
</head>

<body onLoad="message()">
</body>

</html>

Both in the body and head section
<html>
<head>
<script type="text/javascript">
function displayHello() {
alert("Alert Text Here!");
}
</script>
</head>

<body>
<script type="text/javascript">
displayHello();
</script>
</body>

</html>

Scripts using an External JavaScript
<html>
<head>
<script type="text/javascript" src="my_script.js"></script>
</head>

<body>
<script type="text/javascript">
addTwoNumbers ();
</script>
</body>

</html>

//this is the contents of my_script.js
function addTwoNumbers() {
var theSum = 5 + 7;
document.write(Sum is + theSum);
}
/*multi-line comment here. Single line comment is //
This will not be executed
*/
JavaScript Variables
var myNum;
var theName = "Captain James Cook";
myNumber = 5;
document.write("Result: " + theName + " and " + myNum);
//output here will be "Result: Captain James Cook and 5

myNumber = bang bang bang";
document.write(theName + "-" + myNum);
//output here will be "Captain James Cook-bang bang bang"
Rules for JavaScript Variables
case sensitive (y and Y are two different variables).
must begin with a letter or the underscore character.

var emailAdd;
var theAge;
var streetAddress;
var x, y, zNum;
var _mobileNumber;
var COMPANY_NAME;
var helloWorld99, my7X, HTC_1_X;


JavaScript Data Types
String (Howdy)
Number (4.5)
Boolean (true or false)
null
Object (array,date)
Functions (sq=function(x){return x*x;})

var x = 100; //x data type is Number
var y = "55"; //y data type is String
var tempCheck = false; //tempCheck is boolean


JavaScript Operators
Perform arithmetic between variables and/or values.

JavaScript Arithmetic Operators
The + Operator Used on Strings
var txt1 = "You are";
var txt2 = "ugly!";
alert(txt1 + " " + txt2);
//an alert box will display "You are ugly!"

var theRes = 7 + 4;
alert(theRes);
//an alert box will display 11

theRes = "7" + "4";
alert(theRes);
//an alert box will display 74

theRes = 7 + "4";
alert(theRes);
//an alert box will display 74
JavaScript Assignment Operators
var num1 = 10;
num1 += 7; //this means num1=num1+7
//so num1 is now 17

JavaScript Comparison Operators
var num1, num2;
num2 = "5";
num1 = 5;

if (num1 == num2) { //this is true is double equals is used }

if (num1 === num2) { //this is false is triple equals is used }


JavaScript Logical Operators
var myNum1 = 5;
var myNum2 = 7;

if ((myNum1==5) && (myNum2==7)) {
/*this is true*/
}

if ((myNum1==4) || (myNum2==8)) {
//this is false
}
Conditional Statements
if statement
if...else statement
if...else if....else statement
switch statement


var thePass = "123blah";

if (thePass == "123blah") {
alert("Correct Password");
} else if (thePass == "123") {
alert("Almost Correct Password");
} else {
alert("Wrong Password");
}

Switch Example
var myTestNum = 10;

switch(myTestNum) {
case 1:
document.write("Value is 1");
break;
case 5:
document.write("Value is 5");
break;
case 10:
document.write("Value is 10");
break;
default:
document.write("We don't know the value!");
}
For Loop Example
var tempString = ""; //our tempString is empty at first

for (x=1; x<=10; x++) { //variables are allowed NOT to be declared
tempString += x; //this means tempString=tempString+x
/*
You can also replace tempString+=x
with tempString=tempString+x
and get the same result
*/
}

document.write(tempString);
//output will be 12345678910
JavaScript Events
onLoad
onFocus, onBlur, onChange
onMouseOver, onMouseOut, onClick, onKeyDown,
onKeyPress, onKeyUp
onSubmit, onReset
JavaScript Popup Boxes
alert(message)
confirm(message)
prompt(message,defaultText)
Alert Example
var testName1 = "Mario";
var testName2 = "Luigi"

alert("Hello " + testName1 + " and " + testName2);
//output will be "Hello Mario and Luigi"

Confim Example
var userAns;

userAns = confirm("Click OK or click CANCEL");

alert("The user clicked " + userAns);
/*the result will either be
"The user clicked true" if OK is selected OR
"The user clicked false" if Cancel is selected
*/

Confim Example
var person = prompt(What is your name", "Harry Potter");
//Harry Potter will be the default text in the text input

if (person != null) {
alert("Hello " + person + "! How are you today?");
//the output will depend on the person entered
}
JavaScript Functions
Set of JavaScript statements assigned by a name
A function will be executed by an event or by a call to
the function name
Pre-defined functions
parseInt(42) //returns 42
parseInt(42.33) //returns 42
parseFloat(42) // returns 42
parseFloat(42.33) // returns 42.33
3 + 3 + parseInt(3) // returns 9
JavaScript Function Examples
<html>
<head>
<script type="text/javascript">
function sayHi() {
alert("Hi");
}
function sayName(theName) {
alert("Hello " + theName);
}
function addNums(num1, num2) {
var sum = num1+num2;
alert(sum);
}
</script>
</head>

<body>
<input onClick="sayHi();" type="button" value="Say Hi" />
<input onClick="sayName('Xian Lim');" type="button" value="Say Name" />
<input onClick="addNums(5,2);" type="button" value="Add Numbers" />
</body>

</html>
Function and Method
SIMILARITY - both are set of instructions that are
executed if you call their name

DIFFERENCE - method is a member of an object
while a function is not
JavaScript Objects
is a package of data; a collection of properties (variables) and
methods (functions).

How to reference a method and property of
an object?
objectName.propertyName
objectName.methodName(parameters)
Types of JavaScript Object
Built-in JavaScript Objects e.g. Strings, Date, Math
Navigator objects e.g. window, location, history
User-defined objects
String Object Examples
var theName1 = "Jesus Christ"
var theName2 = "Allah";

document.write(theName1 + " is " + theName1.length);
//output here is "Jesus Christ is 12"

document.write(theName2 + " is " + theName2.length);
//output here is "Allah is 5"
String Objects Methods
var myStr = "The quick brown cheetah!";

var tempVar = myStr.indexOf("e");
alert(tempVar);
//tempVar is 2. indexOf("e") returns the index of the first "e"
//also possible myStr.indexOf("e qui"); still returns 2

tempVar = myStr.charAt(5);
alert(tempVar);
//returns 'u'

tempVar = myStr.substr(4,5);
alert(tempVar);
//result is 'brown'
//4 is the start index
//5 is the length of the new sub string
String Objects Methods
var txtOne = "My Nam";
var txtTwo = "e is Juan!"

var newSentence1 = txtOne.concat(txtTwo);
alert(newSentence1);
//result will be "My Name is Juan"

var newSentence2 = txtTwo.concat(txtOne);
alert(newSentence2);
//result will be "e is Juan!My Nam"
JavaScript Arrays
The Array object is used to store multiple values in a single
variable.
Arrays in JavaScript
var nameList = ["Peter", "John", "Joseph"];
var fruits = new Array("Banana", "Apple")

alert(fruits.toString());
//output "Banana,Apple"

alert(nameList.toString());
//output "Peter,John,Joseph"

var newArr = nameList.concat(fruits);
alert(newArr); //works even without the toString()
//output "Peter,John,Joseph,Banana,Apple"

alert(nameList[1]);
//output "John"
Objects in JavaScript
var person1 = {
firstName: "Juan",
lastName: "Tamad",
age: 15
}
alert(JSON.stringify(person1));
/* output here is
{"firstName":"Juan","lastName":"Tamad","age":15}
*/

person1.lastName = "Hardworking";
person1.age = 22;
alert(JSON.stringify(person1));
/*output here is
{"firstName":"Juan","lastName":"Hardworking","age":22}
*/

Das könnte Ihnen auch gefallen