· an html input field was changed an html button was clicked often, when events happen, you may...

46
<! DOCTYPE html > <html> <body> <!-- 1. Datum und Zeit anzeigen --> <h1> Allmann </h1> <button type = "button" onclick = "document.getElementById('absatz').innerHTML = Date()" > Datum und Zeit anzeigen </button> <p id = "absatz" ></p> <!-- 2. Javascript ändert Html-Inhalt --> <h1> Was kann Javascript? </h1> <p id = "id_1" > JavaScript can change HTML content. </p> <button type = "button" onclick = "document.getElementById('id_1').innerHTML = 'Hallo JavaScript!'" > Klick auf mich! </button> <!-- 3. Javascript ändert Html-Attribute - z.B. Bilder --> <h1> JavaScript kann Bilder ändern </h1> <img id = "bild" onclick = "changeImage()" src = "pic_bulboff.gif" width = "100" height = "180" > <p> Click the light bulb to turn on/off the light. </p> <script> function changeImage () { var image = document.getElementById ( 'bild' ); if ( image.src.match ( "bulbon" )) { image.src = "pic_bulboff.gif" ; } else { image.src = "pic_bulbon.gif" ; } } </script> <!-- 4. Javascript ändert Style eines Elementes --> <h1> Was kann Javascript? </h1> <p id = "demo" > JavaScript ändert den style eines HTML-Elementes. </p> <script> function myFunction () { var x = document.getElementById ( "demo" ); x.style.fontSize = "25px" ; x.style.color = "blue" ; } </script> <button type = "button" onclick = "myFunction()" > Click Me! </button> <!-- 5. Javascript validiert Input --> <h1> JavaScript validiert Input </h1> <p> Please input a number between 1 and 10: </p> <input id = "numb" type = "number" > <button type = "button" onclick = "myFunction()" > Submit </button> <p id = "demo" ></p> <script> function myFunction () { var x , text ; // Get the value of the input field with id="numb" x = document.getElementById ( "numb" ). value ; // If x is Not a Number or less than one or greater than 10 if ( isNaN ( x ) || x < 1 || x > 10 ) { text = "Input not valid" ; } else { text = "Input OK" ; } document.getElementById ( "demo" ). innerHTML = text ; } Javascript-Tutorial 1 von 46 Quelle: www.w3schools.com

Upload: others

Post on 18-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<!DOCTYPE html><html><body>

<!-- 1. Datum und Zeit anzeigen --><h1>Allmann</h1><button type="button" onclick="document.getElementById('absatz').innerHTML = Date()">Datum und Zeit anzeigen</button><p id="absatz"></p>

<!-- 2. Javascript ändert Html-Inhalt --><h1>Was kann Javascript?</h1><p id="id_1">JavaScript can change HTML content.</p><button type="button"onclick="document.getElementById('id_1').innerHTML = 'Hallo JavaScript!'">Klick auf mich!</button>

<!-- 3. Javascript ändert Html-Attribute - z.B. Bilder --><h1>JavaScript kann Bilder ändern</h1><img id="bild" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180"><p>Click the light bulb to turn on/off the light.</p><script>function changeImage() { var image = document.getElementById('bild'); if (image.src.match("bulbon")) { image.src = "pic_bulboff.gif"; } else { image.src = "pic_bulbon.gif"; }}</script>

<!-- 4. Javascript ändert Style eines Elementes --><h1>Was kann Javascript?</h1><p id="demo">JavaScript ändert den style eines HTML-Elementes.</p><script>function myFunction() { var x = document.getElementById("demo"); x.style.fontSize = "25px"; x.style.color = "blue"; }</script><button type="button" onclick="myFunction()">Click Me!</button>

<!-- 5. Javascript validiert Input --><h1>JavaScript validiert Input</h1><p>Please input a number between 1 and 10:</p><input id="numb" type="number"><button type="button" onclick="myFunction()">Submit</button><p id="demo"></p><script>function myFunction() { var x, text; // Get the value of the input field with id="numb" x = document.getElementById("numb").value; // If x is Not a Number or less than one or greater than 10 if (isNaN(x) || x < 1 || x > 10) { text = "Input not valid"; } else { text = "Input OK"; } document.getElementById("demo").innerHTML = text;}

Javascript-Tutorial 1 von 46 Quelle: www.w3schools.com

Page 2:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

</script>

<!-- 6. JavaScript kann im head notiert werden --><html><head><script>function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed.";}</script></head><body><h1>JavaScript in Head</h1><p id="demo">A Paragraph.</p><button type="button" onclick="myFunction()">Try it</button></body></html>

<!-- 7. JavaScript kann im body notiert werden --><body><h1>JavaScript in Body</h1><p id="demo">A Paragraph.</p><button type="button" onclick="myFunction()">Try it</button><script>function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed.";}</script></body>

<!-- 8. 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().Eine alert-Box verwenden um Daten anzuzeigen --><h1>My First Web Page</h1><p>My first paragraph.</p><script>window.alert(5 + 6);</script>

<!-- 9. document.write zum Testen verwenden --><h1>My First Web Page</h1><p>My first paragraph.</p><script>document.write(1 + 6);</script>

<!-- 10. document.write() nach geladenem Html-Dokument löscht das ganze Html (soll nur zum Testen verwendet werden)--><body><h1>My First Web Page</h1><p>My first paragraph.</p><button onclick="document.write(5 + 6)">Try it</button></body>

<!-- 11. innerHTML: To access an HTML element, JavaScript can use the document.getElementById(id) method.The id attribute defines the HTML element. The innerHTML property defines the HTML content: --><body><h1>My First Web Page</h1><p>My First Paragraph</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = 5 + 6;

Javascript-Tutorial 2 von 46 Quelle: www.w3schools.com

Page 3:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

</script></body>

<!-- 12. the console.log(): In your browser, you can use the console.log() method to display data.Activate the browser console with F12, and select "Console" in the menu. --><h1>My First Web Page</h1><p>My first paragraph.</p><script>console.log(5 + 6);</script>

<!-- 13. A computer program is a list of "instructions" to be "executed" by the computer. In a programming language, these program instructions are called statements. JavaScript is a programming language. JavaScript statements are separated by semicolon. --><h1>JavaScript Statements</h1><p>Statements are separated by semicolons.</p><p>The variables x, y, and z are assigned the values 5, 6, and 11:</p><p id="demo"></p><script>var x = 5;var y = 6;var z = x + y;document.getElementById("demo").innerHTML = z;</script>

<!-- 14. JavaScript StatementsJavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.JavaScript Values

The JavaScript syntax defines two types of values: Fixed values and variable values.Fixed values are called literals. Variable values are called variables.

JavaScript LiteralsThe most important rules for writing fixed values are:Numbers are written with or without decimals: -->

<h1>JavaScript Numbers</h1><p>Number can be written with or without decimals.</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = 10.50;</script>

<h1>JavaScript Strings</h1><p>Strings can be written with double or single quotes.</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = 'John Doe';</script>

<h1>JavaScript Expressions</h1><p>Expressions compute to values.</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = 5 * 10;</script>

<!-- 15. JavaScript VariablesIn a programming language, variables are used to store data values.JavaScript uses the var keyword to define variables.An equal sign is used to assign values to variables.In this example, x is defined as a variable. Then, x is assigned (given) the value 6: --><h1>JavaScript Variables</h1><p>In this example, x is defined as a variable.Then, x is assigned the value of 6:</p><p id="demo"></p>

Javascript-Tutorial 3 von 46 Quelle: www.w3schools.com

Page 4:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<script>var x;x = 6;document.getElementById("demo").innerHTML = x;</script>

<!-- 16. JavaScript OperatorsJavaScript uses an assignment operator ( = ) to assign values to variables: --><h1>Assigning Values</h1><p>In JavaScript the = operator is used to assign values to variables.</p><p id="demo"></p><script>var x = 5;var y = 6;document.getElementById("demo").innerHTML = x + y;</script><!-- JavaScript uses arithmetic operators ( + - * / ) to compute values: --><h1>JavaScript Operators</h1><p>JavaScript uses arithmetic operators to compute values (just like algebra).</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = (5 + 6) * 10;</script>

<!--- 17. JavaScript Keywords: JavaScript keywords are used to identify actions to be performed. The var keyword tells the browser to create a new variable: --><h1>The var Keyword Creates a Variable</h1><p id="demo"></p><script>var x = 5 + 6;var y = x * 10;document.getElementById("demo").innerHTML = y;</script>

<!-- 18. JavaScript CommentsNot all JavaScript statements are "executed".Code after double slashes // or between /* and */ is treated as a comment.Comments are ignored, and will not be executed -->

<!-- 19. JavaScript is case sensitive: All JavaScript identifiers are case sensitive. The variables lastName and lastname, are two different variables. JavaScript does not interpret VAR or Var as the keyword var.It is common, in JavaScript, to use camelCase names.You will often see names written like lastName (instead of lastname). --><h1>JavaScript is Case Sensitive</h1><p>Try change lastName to lastname.</p><p id="demo"></p><script>var lastName = "Doe";var lastname = "Peterson";document.getElementById("demo").innerHTML = lastName;</script>

<!-- 20. JavaScript Statements: In HTML, JavaScript statements are "instructions" to be "executed" by the web browser.This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo": --><p>In HTML, JavaScript statements are "commands" to the browser.</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = "Hallo Allmann - Hallo Html";</script>

<!-- 21. JavaScript Programs: JavaScript programs (and JavaScript statements) are often called JavaScript code.Most JavaScript programs contain many JavaScript statements.The statements are executed, one by one, in the same order as they are written.

Javascript-Tutorial 4 von 46 Quelle: www.w3schools.com

Page 5:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

In this example, x, y, and z is given values, and finally z is displayed: --><p>JavaScript code (or just JavaScript) is a list of JavaScript statements.</p><p id="demo"></p><script>var x = 5;var y = 6;var z = x + y;document.getElementById("demo").innerHTML = z;</script>

<!-- 22. Semicolons separate JavaScript statements.Add a semicolon at the end of each executable statement: --><p>JavaScript statements are separated by semicolon.</p><p id="demo1"></p><script>a = 1;b = 2;c = a + b;document.getElementById("demo1").innerHTML = c;</script>

<!-- 23. When separated by semicolons, multiple statements on one line are allowed: --><p>Multiple statements on one line is allowed.</p><p id="demo1"></p><script>a = 1; b = 2; c = a + b;document.getElementById("demo1").innerHTML = c;</script>

<!-- 24. JavaScript White Space: JavaScript ignores multiple spaces. You can add white space to your scriptto make it more readable. The following lines are equivalent: -->var person = "Hege";var person="Hege";

<!-- 25. JavaScript Line Length and Line Breaks: For best readability, programmers often like to avoid code lines longer than 80 characters.If a JavaScript statement does not fit on one line, the best place to break it, is after an operator: --><h1>My Web Page</h1><p>The best place to break a code line is after an operator or a comma.</p><p id="demo"></p><script>document.getElementById("demo").innerHTML ="Hello Dolly.";</script>

<!-- 26. JavaScript Code BlocksJavaScript statements can be grouped together in code blocks, inside curly brackets {...}.The purpose of code blocks this is to define statements to be executed together.One place you will find statements grouped together in blocks, are in JavaScript functions: --><h1>My Web Page</h1><p id="myPar">I am a paragraph.</p><div id="myDiv">I am a div.</div><p><button type="button" onclick="myFunction()">Try it</button></p><script>function myFunction() { document.getElementById("myPar").innerHTML = "Hello Dolly."; document.getElementById("myDiv").innerHTML = "How are you?";}</script><p>When you click on "Try it", the two elements will change.</p>

Javascript-Tutorial 5 von 46 Quelle: www.w3schools.com

Page 6:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<!-- 27. JavaScript Keywords: JavaScript keywords are reserved words. Reserved words cannot be used as names for variables. JavaScript statements often start with a keyword to identify the JavaScript action to be performed.Here is a list of some of the keywords you will learn about in this tutorial:Keyword Descriptionbreak Terminates a switch or a loopcontinue Jumps out of a loop and starts at the topdebugger Stops the execution of JavaScript, and calls (if available) the debugging functiondo ... while Executes a block of statements, and repeats the block, while a condition is truefor Marks a block of statements to be executed, as long as a condition is truefunction Declares a functionif ... else Marks a block of statements to be executed, depending on a conditionreturn Exits a functionswitch Marks a block of statements to be executed, depending on different casestry ... catch Implements error handling to a block of statementsvar Declares a variable -->

<!-- 28. JavaScript comments can be used to explain JavaScript code, and to make it more readable.JavaScript comments can also be used to prevent execution, when testing alternative code.Single line comments start with //.Any text between // and the end of a line, will be ignored by JavaScript (will not be executed).This example uses a single line comment before each line, to explain the code: --><h1 id="myH"></h1><p id="myP"></p><script>// Change heading:document.getElementById("myH").innerHTML = "My First Page";// Change paragraph:document.getElementById("myP").innerHTML = "My first paragraph.";</script><p><strong>Note:</strong> The comments are not executed.</p>

<!-- 29. This example uses a single line comment at the end of each line, to explain the code: --><p id="demo"></p><script>var x = 5; // Declare x, give it the value of 5var y = x + 2; // Declare y, give it the value of x + 2 document.getElementById("demo").innerHTML = y; // Write y to demo</script><p><strong>Note:</strong> The comments are not executed.</p>

<!-- 30. Multi-line comments start with /* and end with */.Any text between /* and */ will be ignored by JavaScript.It is most common to use single line comments.Block comments are often used for formal documentation.This example uses a multi-line comment (a comment block) to explain the code: --><h1 id="myH"></h1><p id="myP"></p><script>/*The code below will changethe heading with id = "myH"and the paragraph with id = "myp"in my web page:*/document.getElementById("myH").innerHTML = "My First Page";document.getElementById("myP").innerHTML = "My first paragraph.";</script><p><strong>Note:</strong> The comment block is not executed.</p>

<!-- 31. Using comments to prevent execution of code, are suitable for code testing.Adding // in front of a code line changes the code lines from an executable line to a comment.This example uses // to prevent execution of one of the code lines: --><h1 id="myH"></h1>

Javascript-Tutorial 6 von 46 Quelle: www.w3schools.com

Page 7:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<p id="myP"></p><script>//document.getElementById("myH").innerHTML = "My First Page";document.getElementById("myP").innerHTML = "My first paragraph.";</script><p><strong>Note:</strong> The comment is not executed.</p>

<!-- 32. This example uses a comment block to prevent execution of multiple lines: --><h1 id="myH"></h1><p id="myP"></p><script>/*document.getElementById("myH").innerHTML = "Welcome to my Homepage";document.getElementById("myP").innerHTML = "This is my first paragraph.";*/</script><p><strong>Note:</strong> The comment-block is not executed.</p>

<!-- 33. JavaScript VariablesJavaScript variables are containers for storing data values.In this example, x, y, and z, are variables: --><h1>JavaScript Variables</h1><p>In this example, x and y are variables</p><p id="demo"></p><script>var x = 5;var y = 6;document.getElementById("demo").innerHTML = x + y;</script><!-- From the example above, you can expect: x stores the value 5 y stores the value 6 z stores the value 11 -->

<!-- 34. Much Like AlgebraIn this example, price1, price2, and total, are variables: --><h1>JavaScript Variables</h1><p id="demo"></p><script>var price1 = 5;var price2 = 6;var total = price1 + price2;document.getElementById("demo").innerHTML ="The total is: " + total;</script><!-- In programming, just like in algebra, we use variables (like price1) to hold values.In programming, just like in algebra, we use variables in expressions (total = price1 + price2).From the example above, you can calculate the total to be 11.JavaScript variables are containers for storing data values. -->

<!-- 35. JavaScript IdentifiersAll JavaScript variables must be identified with unique names.These unique names are called identifiers.Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter Names can also begin with $ and _ (but we will not use it in this tutorial) Names are case sensitive (y and Y are different variables) Reserved words (like JavaScript keywords) cannot be used as namesJavaScript identifiers are case-sensitive. -->

<!-- 36. The Assignment OperatorIn JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.

Javascript-Tutorial 7 von 46 Quelle: www.w3schools.com

Page 8:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

This is different from algebra. The following does not make sense in algebra:x = x + 5 In JavaScript however, it makes perfect sense: It assigns the value of x + 5 to x.(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5)The "equal to" operator is written like == in JavaScript. -->

<!-- 37. JavaScript Data TypesJavaScript variables can hold numbers like 100, and text values like "John Doe".In programming, text values are called text strings.JavaScript can handle many types of data, but for now, just think of numbers and strings.Strings are written inside double or single quotes. Numbers are written without quotes.If you put quotes around a number, it will be treated as a text string. --><h1>JavaScript Variables</h1><p>Strings are written with quotes.</p><p>Numbers are written without quotes.</p><p>Try to experiment with the // comments.</p><p id="demo"></p><script>var pi = 3.14;var person = "John Doe";var answer = 'Yes I am!';//document.getElementById("demo").innerHTML = pi;document.getElementById("demo").innerHTML = person;//document.getElementById("demo").innerHTML = answer;</script>

<!-- 38. Declaring (Creating) JavaScript VariablesCreating a variable in JavaScript is called "declaring" a variable.You declare a JavaScript variable with the var keyword:var carName;After the declaration, the variable is empty (it has no value).To assign a value to the variable, use the equal sign:carName = "Volvo";You can also assign a value to the variable when you declare it:var carName = "Volvo";In the example below, we create a variable called carName and assign the value "Volvo" to it.Then we "output" the value inside an HTML paragraph with id="demo": --><h1>JavaScript Variables</h1><p>Create a variable, assign a value to it, and display it:</p><p id="demo"></p><script>var carName = "Volvo";document.getElementById("demo").innerHTML = carName;</script><!-- It's a good programming practice to declare all variables at the beginning of a script. -->

<!-- 39. One Statement, Many VariablesYou can declare many variables in one statement.Start the statement with var and separate the variables by comma: --><h1>JavaScript Variables</h1><p>You can declare many variables in one statement.</p><p id="demo"></p><script>var person = "John Doe", carName = "Volvo", price = 200;document.getElementById("demo").innerHTML = carName;</script><!-- A declaration can span multiple lines: --><h1>JavaScript Variables</h1><p>You can declare many variables in one statement.</p><p id="demo"></p><script>var person = "John Doe",carName = "Volvo",price = 200;

Javascript-Tutorial 8 von 46 Quelle: www.w3schools.com

Page 9:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

document.getElementById("demo").innerHTML = carName;</script>

<!-- 40. Value = undefinedIn computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.A variable declared without a value will have the value undefined.The variable carName will have the value undefined after the execution of this statement: --><h1>JavaScript Variables</h1><p>A variable declared without a value will have the value undefined.</p><p id="demo"></p><script>var carName;document.getElementById("demo").innerHTML = carName;</script><!-- Result in the browser: undefined -->

<!-- 41. Re-Declaring JavaScript VariablesIf you re-declare a JavaScript variable, it will not lose its value.The variable carName will still have the value "Volvo" after the execution of these statements: --><h1>JavaScript Variables</h1><p>If you re-declare a JavaScript variable, it will not lose its value.</p><p id="demo"></p><script>var carName = "Volvo";var carName;document.getElementById("demo").innerHTML = carName;</script><!-- Result in browser: Volvo -->

<!-- 42. JavaScript ArithmeticAs with algebra, you can do arithmetic with JavaScript variables, using operators like = and +: --><h1>JavaScript Variables</h1><p>Add 5 + 2 + 3, and display the result:</p><p id="demo"></p><script>var x = 5 + 2 + 3;document.getElementById("demo").innerHTML = x;</script><!-- You can also add strings, but strings will be concatenated (added end-to-end): --><h1>JavaScript Variables</h1><p>Add "John" + " " + "Doe":</p><p id="demo"></p><script>var x = "John" + " " + "Doe" ;document.getElementById("demo").innerHTML = x;</script><!-- Also try this: --><h1>JavaScript Variables</h1><p>Add "5" + 2 + 3. and display the result:</p><p id="demo"></p><script>var x = "5" + 2 + 3;document.getElementById("demo").innerHTML = x;</script><!-- If you add a number to a string, the number will be treated as string, and concatenated. -->

<!-- exercise 1: Create a variable called carName, assign the value "Volvo" to it, and display it. --><p id="demo">Display the result here.</p> <script>// Create the variable here</script><!-- answer: --><p id="demo">Display the result here.</p>

Javascript-Tutorial 9 von 46 Quelle: www.w3schools.com

Page 10:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<script>var carName = "Volvo";document.getElementById("demo").innerHTML = carName;</script>

<!-- exercise 2: Create a variable called number, assign the value 50 to it, and display it. --><p id="demo">Display the result here.</p> <script>// Create the variable here</script><!-- answer: --><p id="demo">Display the result here.</p> <script>var number = 50;document.getElementById("demo").innerHTML = number;</script>

<!-- exercise 3: The code below should display "Volvo" - Fix it. --><p id="demo">Display the result here.</p> <script>var carName = "Volvo";document.getElementById("demo").innerHTML = carname;</script><!-- answer: --><p id="demo">Display the result here.</p> <script>var carName = "Volvo";document.getElementById("demo").innerHTML = carName;</script>

<!-- exercise 4: Display the sum of 5 + 10, using two variables x and y. --><p id="demo">Display the result here.</p> <script>// Create the variables here</script><!-- answer: --><p id="demo">Display the result here.</p> <script>var x = 5;var y = 10;document.getElementById("demo").innerHTML = x + y;</script>

<!-- 43. JavaScript OperatorsExample:Assign values to variables and add them together: --><h1>JavaScript Operators</h1><p>x = 5, y = 2, calculate z = x + y, and display z:</p><p id="demo"></p><script>var x = 5;var y = 2;var z = x + y;document.getElementById("demo").innerHTML = z;</script>

<!-- a) JavaScript Arithmetic OperatorsArithmetic operators are used to perform arithmetic between variables and/or values.Operator Description+ Addition- Subtraction* Multiplication/ Division% Modulus

Javascript-Tutorial 10 von 46 Quelle: www.w3schools.com

Page 11:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

++ Increment-- Decrement

The addition operator (+) adds a value: --><h1>The + Operator</h1><p id="demo"></p><script>var x = 5;var y = 2;var z = x + y;document.getElementById("demo").innerHTML = z;</script><!-- The subtraction operator (-) subtracts a value.The multiplication operator (*) multiplies a value.The division operator (/) divides a value.The modular operator (%) returns division remainder. --><h1>The % Operator</h1><p id="demo"></p><script>var x = 2.62;var y = 2;var z = x % y;document.getElementById("demo").innerHTML = z;</script><!-- Resultat: 0.6200000000000001 --><!-- 2, 62 dividiert durch 2 ergibt 0.6200000000000001 --><!-- The increment operator (++) increments a value. --><h1>The ++ Operator</h1><p id="demo"></p><script>var x = 5;x++;var z = x;document.getElementById("demo").innerHTML = z;</script><!-- Resultat: 6 --><!-- The decrement operator (--) decrements a value. -->

<!-- b) JavaScript Assignment OperatorsAssignment operators are used to assign values to JavaScript variables.Operator Example Same As= x = y x = y+= x += y x = x + y-= x -= y x = x - y*= x *= y x = x * y/= x /= y x = x / y%= x %= y x = x % y

The = assignment operator assigns a value to a variable: --><h1>The = Operator</h1><p id="demo"></p><script>var x = 12;document.getElementById("demo").innerHTML = x;</script> <!--- Resultat: 12 --><!-- The += assignment operator adds a value to a variable. --><h1>The += Operator</h1><p id="demo"></p><script>var x = 10;x += 5;document.getElementById("demo").innerHTML = x;</script> <!--- Resultat: 15 --><!-- The -= assignment operator subtracts a value from a variable.The *= assignment operator multiplies a variable. -->

Javascript-Tutorial 11 von 46 Quelle: www.w3schools.com

Page 12:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<h1>The *= Operator</h1><p id="demo"></p><script>var x = 10;x *= 5;document.getElementById("demo").innerHTML = x;</script> <!-- result: 50 --><!-- The /= assignment divides a variable. --><h1>The /= Operator</h1><p id="demo"></p><script>var x = 10;x /= 5;document.getElementById("demo").innerHTML = x;</script> <!-- result: 2 --><!-- The %= assignment operator assigns a remainder to a variable. --><h1>The %= Operator</h1><p id="demo"></p><script>var x = 10;x %= 9.2;document.getElementById("demo").innerHTML = x;</script> <!-- result: 0.8000000000000007 -->

<!-- c) JavaScript String OperatorsThe + operator can also be used to concatenate (add) strings.Note: When used on strings, the + operator is called the concatenation operator.Example: To add two or more string variables together, use the + operator. --><!-- txt1 = "What a very";

txt2 = "nice day"; txt3 = txt1 + txt2;

The result of txt3 will be:What a verynice day --><h1>JavaScript Operators</h1><p>The + operator concatenates (adds) strings.</p><p id="demo"></p><script>var txt1 = "What a very";var txt2 = "nice day";document.getElementById("demo").innerHTML = txt1 + txt2;</script><!-- To add a space between the two strings, insert a space into one of the strings: txt1 = "What a very ";txt2 = "nice day";txt3 = txt1 + txt2;The result of txt3 will be:What a very nice day --></script>

<!-- ... or insert a space into the expression: --><h1>JavaScript Operators</h1><p>The + operator concatenates (adds) strings.</p><p id="demo"></p><script>var txt1 = "What a very";var txt2 = "nice day";document.getElementById("demo").innerHTML = txt1 + " " + txt2;</script><!-- The += operator can also be used to concatenate strings: --><p id="demo"></p><script>txt1 = "What a very ";txt1 += "nice day.";document.getElementById("demo").innerHTML = txt1;

Javascript-Tutorial 12 von 46 Quelle: www.w3schools.com

Page 13:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

</script>

<!-- d) Adding Strings and NumbersAdding two numbers, will return the sum, but adding a number and a string will return a string: --><p>If you add a number and a string, the result will be a string!</p><p id="demo"></p><script>var x = 5 + 5;var y = "5" + 5;var z = "Hello" + 5;document.getElementById("demo").innerHTML =x + "<br>" + y + "<br>" + z;</script> <!-- result:1055Hello5 --><!-- Comparison and logical operators are described in the JS Comparisons chapter. -->

<!-- 44. JavaScript Data TypesJavaScript variables can hold many data types: numbers, strings, arrays, objects and more: --><!-- var length = 16; // Numbervar lastName = "Johnson"; // Stringvar cars = ["Saab", "Volvo", "BMW"]; // Arrayvar x = {firstName:"John", lastName:"Doe"}; // Object -->

<!-- 45. The Concept of Data TypesIn programming, data types is an important concept.To be able to operate on variables, it is important to know something about the type.Without data types, a computer cannot safely solve this:var x = 16 + "Volvo";Does it make any sense to add "Volvo" to sixteen? Will produce a result? Will it produce an error?JavaScript will treat the example above as:var x = "16" + "Volvo";Note: If the second operand is a string, JavaScript will also treat the first operand as a string. Example:var x = 16 + "Volvo"; --><p id="demo"></p><script>var x = 16 + "Volvo";document.getElementById("demo").innerHTML = x;</script><!-- result: 16volvo --><!-- JavaScript evaluates expressions from left to right. Different sequences can produce different results:JavaScript: var x = 16 + 4 + "Volvo";Result: 20Volvo --><p id="demo"></p><script>var x = 16 + 4 + "Volvo";document.getElementById("demo").innerHTML = x;</script><!-- result: 20volvo --><!-- JavaScript: var x = "Volvo" + 16 + 4;Result: Volvo164 --><p id="demo"></p><script>var x = "Volvo" + 16 + 4;document.getElementById("demo").innerHTML = x;</script><!-- In the first example, JavaScript treat 16 and 3 as numbers, until it reaches "Volvo".In the second example, since the first operand is a string, all operands are treated as strings. -->

<!-- 46. JavaScript Has Dynamic TypesJavaScript has dynamic types. This means that the same variable can be used as different types:Example:var x; // Now x is undefined

Javascript-Tutorial 13 von 46 Quelle: www.w3schools.com

Page 14:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var x = 5; // Now x is a Numbervar x = "John"; // Now x is a String -->

<!-- 47. JavaScript StringsA string (or a text string) is a series of characters like "John Doe".Strings are written with quotes. You can use single or double quotes:Examplevar carName = "Volvo XC60"; // Using double quotesvar carName = 'Volvo XC60'; // Using single quotesYou can use quotes inside a string, as long as they don't match the quotes surrounding the string:Examplevar answer = "It's alright"; // Single quote inside double quotesvar answer = "He is called 'Johnny'"; // Single quotes inside double quotesvar answer = 'He is called "Johnny"'; // Double quotes inside single quotes --><p id="demo"></p><script>var carName1 = "Volvo XC60";var carName2 = 'Volvo XC60';var answer1 = "It's alright";var answer2 = "He is called 'Johnny'";var answer3 = 'He is called "Johnny"';document.getElementById("demo").innerHTML =carName1 + "<br>" + carName2 + "<br>" + answer1 + "<br>" + answer2 + "<br>" + answer3;</script> <!-- result: Volvo XC60Volvo XC60It's alrightHe is called 'Johnny'He is called "Johnny" -->

<!-- 48. JavaScript NumbersJavaScript has only one type of numbers.Numbers can be written with, or without decimals:Examplevar x1 = 34.00; // Written with decimalsvar x2 = 34; // Written without decimalsExtra large or extra small numbers can be written with scientific (exponential) notation:Examplevar y = 123e5; // 12300000var z = 123e-5; // 0.00123 --><p id="demo"></p><script>var x1 = 34.00;var x2 = 34;var y = 123e5;var z = 123e-5;document.getElementById("demo").innerHTML = x1 + "<br>" + x2 + "<br>" + y + "<br>" + z</script><!-- result: 3434123000000.00123 -->

<!-- 49. JavaScript BooleansBooleans can only have two values: true or false.Examplevar x = true;var y = false;Booleans are often used in conditional testing.You will learn more about conditional testing later in this tutorial.

Javascript-Tutorial 14 von 46 Quelle: www.w3schools.com

Page 15:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

50. JavaScript ArraysJavaScript arrays are written with square brackets.Array items are separated by commas.The following code declares (creates) an array called cars, containing three items (car names):Examplevar cars = ["Saab", "Volvo", "BMW"]; --><p id="demo"></p><script>var cars = ["Saab","Volvo","BMW"];document.getElementById("demo").innerHTML = cars[0];</script><!-- result: Saab --><!-- Array indexes are zero-based, which means the first item is [0], second is [1], and so on. -->

<!-- 51. JavaScript ObjectsJavaScript objects are written with curly braces.Object properties are written as name:value pairs, separated by commas.Examplevar person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};--><p id="demo"></p><script>var person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue"};document.getElementById("demo").innerHTML =person.firstName + " is " + person.age + " years old.";</script><!-- result: John is 50 years old. --><!-- The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor. -->

<!-- 52. The typeof OperatorYou can use the JavaScript typeof operator to find the type of a JavaScript variable:Exampletypeof "John" // Returns stringtypeof 3.14 // Returns numbertypeof false // Returns booleantypeof [1,2,3,4] // Returns objecttypeof {name:'John', age:34} // Returns object --><!-- In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object. --><p>The typeof operator returns the type of a variable or an expression.</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = typeof "john" + "<br>" + typeof 3.14 + "<br>" +typeof false + "<br>" +typeof [1,2,3,4] + "<br>" +typeof {name:'john', age:34};</script><!-- result: stringnumberbooleanobjectobject -->

<!-- 53. UndefinedIn JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.Examplevar person; // The value is undefined, the typeof is undefined --><p>Both the value, and the data type, of a variable with no value is <b>undefined</b>.</p><p id="demo"></p><script>var person;document.getElementById("demo").innerHTML =

Javascript-Tutorial 15 von 46 Quelle: www.w3schools.com

Page 16:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

person + "<br>" + typeof person;</script><!-- result: undefinedundefined -->

<!-- 54. Empty ValuesAn empty value has nothing to do with undefined.An empty string variable has both a value and a type.Examplevar car = ""; // The value is "", the typeof is string --><p id="demo"></p><script>var car = "";document.getElementById("demo").innerHTML ="The value is: " +car + "<br>" +"The type is:" + typeof car;</script><!-- result: The value is:The type is:string -->

<!-- 55. JavaScript FunctionsA JavaScript function is a block of code designed to perform a particular task.A JavaScript function is executed when "something" invokes it (calls it).Examplefunction myFunction(p1, p2) { return p1 * p2; // The function returns the product of p1 and p2} --><p>This example calls a function which performs a calculation, and returns the result:</p><p id="demo"></p><script>function myFunction(a, b) { return a * b;}document.getElementById("demo").innerHTML = myFunction(4, 3);</script><!-- result: 12 -->

<!-- 56. JavaScript Function SyntaxA JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)The code to be executed, by the function, is placed inside curly brackets: {}functionName(parameter1, parameter2, parameter3) { code to be executed}Function parameters are the names listed in the function definition.Function arguments are the real values received by the function when it is invoked.Inside the function, the arguments are used as local variables.Note: A Function is much the same as a Procedure or a Subroutine, in other programming languages. -->

<!-- 57. Function InvocationThe code inside the function will execute when "something" invokes (calls) the function: When an event occurs (when a user clicks a button) When it is invoked (called) from JavaScript code Automatically (self invoked)You will learn a lot more about function invocation later in this tutorial. -->

<!-- 58. Function ReturnWhen JavaScript reaches a return statement, the function will stop executing.If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.Functions often compute a return value. The return value is "returned" back to the "caller":ExampleCalculate the product of two numbers, and return the result:var x = myFunction(4, 3); // Function is called, return value will end up in xfunction myFunction(a, b) {

Javascript-Tutorial 16 von 46 Quelle: www.w3schools.com

Page 17:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

return a * b; // Function returns the product of a and b}The result in x will be: 12 --><p>This example calls a function which performs a calculation, and returns the result:</p><p id="demo"></p><script>function myFunction(a, b) { return a * b;}document.getElementById("demo").innerHTML = myFunction(4, 3);</script><!-- result: 12 -->

<!-- 59. Why Functions?You can reuse code: Define the code once, and use it many times.You can use the same code many times with different arguments, to produce different results.ExampleConvert Fahrenheit to Celsius:function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32);}document.getElementById("demo").innerHTML = toCelsius(32); --><p>This example calls a function to convert from Fahrenheit to Celsius:</p><p id="demo"></p><script>function toCelsius(f) { return (5/9) * (f-32);}document.getElementById("demo").innerHTML = toCelsius(32);</script><!-- result: 0 -->

<!-- 60. The () Operator Invokes the FunctionUsing the example above, toCelsius refers to the function object, and toCelcius() refers to the function result.ExampleAccessing a function without () will return the function definition:function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32);}document.getElementById("demo").innerHTML = toCelsius; --><p>Accessing a function without (), will return the function definition:</p><p id="demo"></p><script>function toCelsius(f) { return (5/9) * (f-32);}document.getElementById("demo").innerHTML = toCelsius;//document.getElementById("demo").innerHTML = toCelsius(32);</script><!-- result: function toCelsius(f) { return (5/9) * (f-32); } -->

<!-- 61. Functions Used as VariablesIn JavaScript, functions can be used as variables:ExampleInstead of:temp = toCelsius(32);text = "The temperature is " + temp + " Centigrade";You can use:text = "The temperature is " + toCelsius(32) + " Centigrade"; --><p id="demo"></p><script>document.getElementById("demo").innerHTML ="The temperature is " + toCelsius(32) + " Centigrade";function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32);} </script><!-- result: The temperature is 0 Centigrade -->

Javascript-Tutorial 17 von 46 Quelle: www.w3schools.com

Page 18:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<!-- exercise 1: Call the function:--><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = "Hello World!";}</script><!-- answer to ex. 1 --><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = "Hello World!";}myFunction();</script>

<!-- exercise 2: Figure out what is wrong with the function - fix it and run it as it should! --><p id="demo"></p><script>func myFunc { document.getElementById("demo").innerHTML = "Hello World!";}myFunction();</script><!-- answer: --><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = "Hello World!";}myFunction();</script>

<!-- exercise 3: Use the function to display the sum of 5 * 5. --><p id="demo"></p><script>function myFunction() { // add code here}document.getElementById("demo").innerHTML = myFunction();</script><!-- answer: --><p id="demo"></p><script>function myFunction() { return 5 * 5;}document.getElementById("demo").innerHTML = myFunction();</script>

<!-- exercise 4: Use the function to display "Hello John". --><p id="demo">Display the result here.</p><script>function myFunction(name) { return "Hello " + name;}</script><!-- answer: --><p id="demo">Display the result here.</p><script>function myFunction(name) { return "Hello " + name;}

Javascript-Tutorial 18 von 46 Quelle: www.w3schools.com

Page 19:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

document.getElementById("demo").innerHTML = myFunction("John");</script>

<!-- exercise 5: Define a function named "myFunction", and make it display "Hello World" in the <p> element --><p id="demo">Display the result here.</p><script>// Define and call the function here</script><!-- answer: --><p id="demo">Display the result here.</p><script>function myFunction() { document.getElementById("demo").innerHTML = "Hello World!";}myFunction();</script>

<!-- 62. JavaScript Objects Real Life Objects, Properties, and MethodsIn real life, a car is an object. A car has properties like weight and color, and methods like start and stop:Object: a Fiat 500 Properties: car.name = Fiatcar.model = 500car.weight = 850kgcar.color = white Methods:car.start()car.drive()car.brake()car.stop()All cars have the same properties, but the property values differ from car to car.All cars have the same methods, but the methods are performed at different times. -->

<!-- 63. JavaScript ObjectsYou have already learned that JavaScript variables are containers for data values.This code assigns a simple value (Fiat) to a variable named car:var car = "Fiat"; --><p>Creating a JavaScript Variable.</p><p id="demo"></p><script>var car = "Fiat";document.getElementById("demo").innerHTML = car;</script> <!-- result: Fiat --><!-- Objects are variables too. But objects can contain many values.This code assigns many values (Fiat, 500, white) to a variable named car:var car = {type:"Fiat", model:500, color:"white"}; --><p>Creating a JavaScript Object.</p><p id="demo"></p><script>var car = {type:"Fiat", model:500, color:"white"};document.getElementById("demo").innerHTML = car.type;</script> <!-- Fiat --><!-- The values are written as name:value pairs (name and value separated by a colon).Note JavaScript objects are containers for named values. -->

<!-- 64. Object PropertiesThe name:values pairs (in JavaScript objects) are called properties.var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};Property Property ValuefirstName JohnlastName Doeage 50eyeColor blue -->

Javascript-Tutorial 19 von 46 Quelle: www.w3schools.com

Page 20:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<!-- 65. Object MethodsMethods are actions that can be performed on objects.Methods are stored in properties as function definitions.Property Property ValuefirstName JohnlastName Doeage 50eyeColor bluefullName function() {return this.firstName + " " + this.lastName;}Note: JavaScript objects are containers for named values, called properties and methods. -->

<!-- 66. Object DefinitionYou define (and create) a JavaScript object with an object literal:Examplevar person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; --><p>Creating a JavaScript Object.</p><p id="demo"></p><script>var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};document.getElementById("demo").innerHTML =person.firstName + " is " + person.age + " years old.";</script><!-- John is 50 years old. --><!-- Spaces and line breaks are not important. An object definition can span multiple lines:Examplevar person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; -->

<!-- 67. Accessing Object PropertiesYou can access object properties in two ways:objectName.propertyNameorobjectName[propertyName]

Example1:person.lastName; --><p>There are two different ways to access an object property: </p><p>You can use person.property or person["property"].</p><p id="demo"></p><script>var person = { firstName: "John", lastName : "Doe", id : 5566};document.getElementById("demo").innerHTML =person.firstName + " " + person.lastName;</script> <!--result: John Doe -->

<!-- Example2:person["lastName"]; --><p>There are two different ways to access an object property: </p><p>You can use person.property or person["property"].</p><p id="demo"></p><script>var person = {

Javascript-Tutorial 20 von 46 Quelle: www.w3schools.com

Page 21:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

firstName: "John", lastName : "Doe", id : 5566};document.getElementById("demo").innerHTML =person["firstName"] + " " + person["lastName"];</script><!--result: John Doe -->

<!-- 68. Accessing Object MethodsYou access an object method with the following syntax:objectName.methodName()Example:name = person.fullName(); --><p>Creating and using an object method.</p><p>An object method is a function definition, stored as a property value.</p><p id="demo"></p><script>var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function(c) { return this.firstName + " " + this.lastName; }};document.getElementById("demo").innerHTML = person.fullName();</script><!-- result: John Doe --><!-- If you access the fullName property, without (), it will return the function definition:Example: name = person.fullName; --><p>An object method is a function definition, stored as a property value.</p><p>If you access it without (), it will return the function definition:</p><p id="demo"></p><script>var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; }};document.getElementById("demo").innerHTML = person.fullName;</script><!-- function () { return this.firstName + " " + this.lastName; } -->

<!-- 69. Do Not Declare Strings, Numbers, and Booleans as Objects!When a JavaScript variable is declared with the keyword "new", the variable is created as an object:var x = new String(); // Declares x as a String objectvar y = new Number(); // Declares y as a Number objectvar z = new Boolean(); // Declares z as a Boolean objectAvoid String, Number, and Boolean objects. They complicate your code and slow down execution speed. --><!-- Exercise 1:Display "John" by using information from the person object.Hint: Access the firstName property (like objectName.propertyName) --><p id="demo">Display the result here.</p><script>var person = {firstName:"John", lastName:"Doe"};</script><!-- answer: --><p id="demo">Display the result here.</p><script>var person = {firstName:"John", lastName:"Doe"};document.getElementById("demo").innerHTML = person.firstName;</script><!-- result: John --><!-- Exercise 2:

Javascript-Tutorial 21 von 46 Quelle: www.w3schools.com

Page 22:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

Add the following property and value to the person object, and display it:country: USA --><p id="demo">Display the result here.</p><script>var person = {firstName:"John", lastName:"Doe"};</script><!-- answer: --><p id="demo">Display the result here.</p>

<script>var person = {firstName:"John", lastName:"Doe", country: "USA"};document.getElementById("demo").innerHTML = person.country;</script><!-- USA -->

<!-- 70. JavaScript ScopeScope is the set of variables you have access to.In JavaScript, objects and functions, are also variables.In JavaScript, scope is the set of variables, objects, and functions you have access to.JavaScript has function scope: The scope changes inside functions. -->

<!-- 71. Local JavaScript VariablesVariables declared within a JavaScript function, become LOCAL to the function.Local variables have local scope: They can only be accessed within the function.Example:// code here can not use carNamefunction myFunction() { var carName = "Volvo"; // code here can use carName} --><p>A local variable can only be accessed from within the function where it was declared.</p><p id="demo"></p><script>myFunction();document.getElementById("demo").innerHTML ="I can display " + typeof carName;function myFunction() { var carName = "Volvo";}</script><!-- result: I can display undefined --><!-- Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.Local variables are created when a function starts, and deleted when the function is completed. -->

<!-- 72. Global JavaScript VariablesA variable declared outside a function, becomes GLOBAL.A global variable has global scope: All scripts and functions on a web page can access it. Examplevar carName = " Volvo";// code here can use carNamefunction myFunction() { // code here can use carName} --><p>A GLOBAL variable can be accessed from any script or function.</p><p id="demo"></p><script>var carName = "Volvo";myFunction();function myFunction() { document.getElementById("demo").innerHTML = "I can display " + carName;}</script><!--- I can display Volvo -->

<!-- 73. Automatically GlobalIf you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

Javascript-Tutorial 22 von 46 Quelle: www.w3schools.com

Page 23:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

This code example will declare carName as a global variable, even if it is executed inside a function.Example// code here can use carNamefunction myFunction() { carName = "Volvo"; // code here can use carName} --><p>If you assign a value to a variable that has not been declared,it will automatically become a GLOBAL variable:</p>

<p id="demo"></p>

<script>myFunction();document.getElementById("demo").innerHTML ="I can display " + carName;

function myFunction() { carName = "Volvo";}</script><!-- I can display Volvo -->

<!-- 74. The Lifetime of JavaScript VariablesThe lifetime of a JavaScript variable starts when it is declared.Local variables are deleted when the function is completed.Global variables are deleted when you close the page. -->

<!-- 75. Function ArgumentsFunction arguments (parameters) work as local variables inside functions. -->

<!-- 76. Global Variables in HTMLWith JavaScript, the global scope is the complete JavaScript environment.In HTML, the global scope is the window object: All global variables belong to the window object.Example// code here can use window.carNamefunction myFunction() { carName = "Volvo";} --><p>In HTML, all global variables will become a window variables.</p><p id="demo"></p><script>myFunction();document.getElementById("demo").innerHTML ="I can display " + window.carName;function myFunction() { carName = "Volvo";}</script><!-- I can display Volvo --><!-- Did You Know?Your global variables, or functions, can overwrite window variables or functions.Anyone, including the window object, can overwrite your global variables or functions. -->

<!-- 77. JavaScript EventsHTML events are "things" that happen to HTML elements.When JavaScript is used in HTML pages, JavaScript can "react" on these events. -->

<!-- 78. HTML EventsAn HTML event can be something the browser does, or something a user does.Here are some examples of HTML events: An HTML web page has finished loading

Javascript-Tutorial 23 von 46 Quelle: www.w3schools.com

Page 24:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

An HTML input field was changed An HTML button was clickedOften, when events happen, you may want to do something.JavaScript lets you execute code when events are detected.HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.With single quotes:<some-HTML-element some-event='some JavaScript'>With double quotes:<some-HTML-element some-event="some JavaScript">In the following example, an onclick attribute (with code), is added to a button element:Example:<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button> --><button onclick="getElementById('demo').innerHTML=Date()">The time is?</button><p id="demo"></p><!-- result: Button mit Caption "The time is?" und Sun Feb 22 2015 09:43:59 GMT+0100 -->

<!-- JavaScript code is often several lines long. It is more common to see event attributes calling functions:Example: <button onclick="displayDate()">The time is?</button> --><p>Click the button to display the date.</p><button onclick="displayDate()">The time is?</button><script>function displayDate() { document.getElementById("demo").innerHTML = Date();}</script><p id="demo"></p>

<!-- 79. Common HTML EventsHere is a list of some common HTML events:Event Descriptiononchange An HTML element has been changedonclick The user clicks an HTML elementonmouseover The user moves the mouse over an HTML elementonmouseout The user moves the mouse away from an HTML elementonkeydown The user pushes a keyboard keyonload The browser has finished loading the pageThe list is much longer: link to: W3Schools JavaScript Reference HTML DOM Events. -->

<!-- 80. What can JavaScript Do?Event handlers can be used to handle, and verify, user input, user actions, and browser actions: Things that should be done every time a page loads Things that should be done when the page is closed Action that should be performed when a user clicks a button Content that should be verified when a user input data And more ...Many different methods can be used to let JavaScript work with events: HTML event attributes can execute JavaScript code directly HTML event attributes can call JavaScript functions You can assign your own event handler functions to HTML elements You can prevent events from being sent or being handled And more ...Note You will learn a lot more about events and event handlers in the HTML DOM chapters. -->

<!-- Exercise:Fix the <p> element to display "Hello" when someone clicks on it.Hint: Use an onclick event. --><p someevent="this.innerHTML='Hello'">Click me.</p><!-- answer: --><p onclick="this.innerHTML='Hello'">Click me.</p>

<!-- Exercise:When the button is clicked, trigger myFunction() with an event.Hint: Add an onclick event. --><button>Click Me</button><p id="demo"></p>

Javascript-Tutorial 24 von 46 Quelle: www.w3schools.com

Page 25:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<script>function myFunction() { document.getElementById("demo").innerHTML = "Hello World";}</script><!-- answer: --><button onclick="myFunction()">Click Me</button><p id="demo"></p> <script>function myFunction() { document.getElementById("demo").innerHTML = "Hello World";}</script>

<!-- 81. JavaScript StringsJavaScript strings are used for storing and manipulating text.A JavaScript string simply stores a series of characters like "John Doe".A string can be any text inside quotes. You can use single or double quotes:Examplevar carname = "Volvo XC60";var carname = 'Volvo XC60'; --><p id="demo"></p><script>var carName1 = "Volvo XC60";var carName2 = 'Volvo XC60';document.getElementById("demo").innerHTML =carName1 + "<br>" + carName2; </script><!-- result: Volvo XC60Volvo XC60 --><!-- You can use quotes inside a string, as long as they don't match the quotes surrounding the string:Examplevar answer = "It's alright";var answer = "He is called 'Johnny'";var answer = 'He is called "Johnny"'; --><p id="demo"></p><script>var answer1 = "It's alright";var answer2 = "He is called 'Johnny'";var answer3 = 'He is called "Johnny"'; document.getElementById("demo").innerHTML =answer1 + "<br>" + answer2 + "<br>" + answer3; </script><!-- result: It's alrightHe is called 'Johnny'He is called "Johnny" -->

<!-- 82. String LengthThe length of a string is found in the built in property length:Examplevar txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";var sln = txt.length; --><p id="demo"></p><script>var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";document.getElementById("demo").innerHTML = txt.length;</script><!-- result: 26 -->

<!-- 83. Special CharactersBecause strings must be written within quotes, JavaScript will misunderstand this string:var y = "We are the so-called "Vikings" from the north."The string will be chopped to "We are the so-called ".The solution to avoid this problem, is to use the \ escape character.The backslash escape character turns special characters into string characters:Examplevar x = 'It\'s alright';

Javascript-Tutorial 25 von 46 Quelle: www.w3schools.com

Page 26:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var y = "We are the so-called \"Vikings\" from the north." --><p id="demo"></p><script>var x = 'It\'s alright';var y = "We are the so-called \"Vikings\" from the north.";document.getElementById("demo").innerHTML = x + "<br>" + y; </script><!-- result: It's alrightWe are the so-called "Vikings" from the north. -->

<!-- The escape character (\) can also be used to insert other special characters in a string.This is the lists of special characters that can be added to a text string with the backslash sign:Code Outputs\' single quote\" double quote\\ backslash\n new line\r carriage return\t tab\b backspace\f form feed -->

<!-- 84. Breaking Long Code LinesFor best readability, programmers often like to avoid code lines longer than 80 characters.If a JavaScript statement does not fit on one line, the best place to break it, is after an operator:Exampledocument.getElementById("demo").innerHTML ="Hello Dolly."; --><!-- You can also break up a code line within a text string with a single backslash:Exampledocument.getElementById("demo").innerHTML = "Hello \Dolly!"; --><!-- However, you cannot break up a code line with a backslash:Exampledocument.getElementById("demo").innerHTML = \"Hello Dolly!"; -->

<!-- 85. Strings Can be ObjectsNormally, JavaScript strings are primitive values, created from literals: var firstName = "John"But strings can also be defined as objects with the keyword new: var firstName = new String("John")Examplevar x = "John";var y = new String("John");// type of x will return String// type of y will return Object --><p id="demo"></p><script>var x = "John"; // x is a stringvar y = new String("John"); // y is an objectdocument.getElementById("demo").innerHTML =typeof x + "<br>" + typeof y;</script><!-- result: stringobject --><!-- Note: Don't create strings as objects. It slows down execution speed, and produces nasty side effects:When using the == equality operator, equal strings looks equal:Examplevar x = "John"; var y = new String("John");// (x == y) is true because x and y have equal values --><p>Never create strings as objects.</p><p>Stings and objects cannot be safely compared.</p><p id="demo"></p><script>var x = "John"; // x is a string

Javascript-Tutorial 26 von 46 Quelle: www.w3schools.com

Page 27:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var y = new String("John"); // y is an objectdocument.getElementById("demo").innerHTML = (x==y) +"<br>" + (x===y);</script><!-- result: truefalse --><!-- When using the === equality operator, equal strings are not equal, because the === operator expects equality in both type and value.Examplevar x = "John"; var y = new String("John");// (x === y) is false because x and y have different types --><p>Never create strings as objects.</p><p>Stings and objects cannot be safely compared.</p><p id="demo"></p><script>var x = "John"; // x is a stringvar y = new String("John"); // y is an objectdocument.getElementById("demo").innerHTML = (x===y);</script><!-- result: false --><!-- Or ever worse. Different objects cannot be compared:Examplevar x = new String("John"); var y = new String("John");// (x == y) is false because objects cannot be compared --><p>Never create strings as objects.</p><p>Objects cannot be safely compared.</p><p id="demo"></p><script>var x = new String("John"); // x is an objectvar y = new String("John"); // y is an objectdocument.getElementById("demo").innerHTML = (x==y);</script><!-- result: false --><!-- Objects cannot be compared. -->

<!-- 86. String Properties and MethodsPrimitive values, like "John Doe", cannot have properties or methods (because they are not objects).But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.String methods are covered in next chapter.

String PropertiesProperty Descriptionconstructor Returns the function that created the String object's prototypelength Returns the length of a stringprototype Allows you to add properties and methods to an object

String MethodsMethod DescriptioncharAt() Returns the character at the specified index (position)charCodeAt() Returns the Unicode of the character at the specified indexconcat() Joins two or more strings, and returns a copy of the joined stringsfromCharCode() Converts Unicode values to charactersindexOf() Returns the position of the first found occurrence of a specified value in a stringlastIndexOf() Returns the position of the last found occurrence of a specified value in a stringlocaleCompare() Compares two strings in the current localematch() Searches a string for a match against a regular expression, and returns the matchesreplace() Searches a string for a value and returns a new string with the value replacedsearch() Searches a string for a value and returns the position of the matchslice() Extracts a part of a string and returns a new stringsplit() Splits a string into an array of substringssubstr() Extracts a part of a string from a start position through a number of characterssubstring() Extracts a part of a string between two specified positionstoLocaleLowerCase() Converts a string to lowercase letters, according to the host's localetoLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale

Javascript-Tutorial 27 von 46 Quelle: www.w3schools.com

Page 28:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

toLowerCase() Converts a string to lowercase letterstoString() Returns the value of a String objecttoUpperCase() Converts a string to uppercase letterstrim() Removes whitespace from both ends of a stringvalueOf() Returns the primitive value of a String object -->

<!-- Exercise 1: Assign the string "Hello World!" to the variable txt, and display it.Hint: Remember that strings should be surrounded by quotes. --><p id="demo">Display the result here.</p> <script>var txt;</script><!-- answer --><p id="demo">Display the result here.</p> <script>var txt = "Hello World!";document.getElementById("demo").innerHTML = txt;</script><!-- Hello World -->

<!-- Exercise 2: Display the length of the txt variable's value. Hint: Use the length property. --><p id="demo">Display the result here.</p> <script>var txt = "Hello World!";</script><!-- answer --><p id="demo">Display the result here.</p> <script>var txt = "Hello World!";document.getElementById("demo").innerHTML = txt.length;</script><!-- 12 -->

<!-- Exercise 3: The string below is broken - use escape characters to display the text correctly.Hint: Use \"Vikings\". --><p id="demo"></p> <script>document.getElementById("demo").innerHTML = "We are "Vikings"."; </script><p id="demo"></p> <script>document.getElementById("demo").innerHTML = "We are \"Vikings\"."; </script><!-- We are "Vikings". -->

<!-- Exercise 4: Use the addition operator (+) to concatenate the two strings.Hint: Output str1 + str2. --><p id="demo">Display the result here.</p> <script>var str1 = "Hello ";var str2 = "World!";</script><!-- answer --><p id="demo">Display the result here.</p> <script>var str1 = "Hello ";var str2 = "World!";document.getElementById("demo").innerHTML = str1 + str2;</script><!-- result: Hello World -->

<!-- 87. JavaScript String Methods: String methods help you to work with strings.Finding a String in a StringThe indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.indexOf("locate"); -->

Javascript-Tutorial 28 von 46 Quelle: www.w3schools.com

Page 29:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<body><p id="p1">Please locate where 'locate' occurs!.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var str = document.getElementById("p1").innerHTML; var pos = str.indexOf("locate"); document.getElementById("demo").innerHTML = pos;}</script><!-- result: 7 --><!-- The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.lastIndexOf("locate"); --><p id="p1">Please locate where 'locate' occurs!.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var str = document.getElementById("p1").innerHTML; var pos = str.lastIndexOf("locate"); document.getElementById("demo").innerHTML = pos;}</script><!-- result: 21 --><!-- Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.Note: JavaScript counts positions from zero.0 is the first position in a string, 1 is the second, 2 is the third ...Both methods accept a second parameter as the starting position for the search.

88. Searching for a String in a StringThe search() method searches a string for a specified value and returns the position of the match:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.search("locate"); --><p id="p1">Please locate where 'locate' occurs!.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var str = document.getElementById("p1").innerHTML; var pos = str.search("locate"); document.getElementById("demo").innerHTML = pos;}</script><!-- result: 7 --><!-- Note: Did You Notice?The two methods, indexOf() and search(), are equal.They accept the same arguments (parameters), and they return the same value.The two methods are equal, but the search() method can take much more powerful search values.You will learn more about powerful search values in the chapter about regular expressions.

89. Extracting String PartsThere are 3 methods for extracting a part of a string:

slice(start, end)substring(start, end)substr(start, length)

a) The slice() Methodslice() extracts a part of a string and returns the extracted part in a new string.The method takes 2 parameters: the starting index (position), and the ending index (position).This example slices out a portion of a string from position 7 to position 13:Example

Javascript-Tutorial 29 von 46 Quelle: www.w3schools.com

Page 30:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var str = "Apple, Banana, Kiwi";var res = str.slice(7,13);The result of res will be: Banana --><p>The slice() method extract a part of a stringand returns the extracted parts in a new string:</p><p id="demo"></p><script>var str = "Apple, Banana, Kiwi";document.getElementById("demo").innerHTML = str.slice(7,13);</script><!-- result: banana--><!-- If a parameter is negative, the position is counted from the end of the string.This example slices out a portion of a string from position -12 to position -6:Examplevar str = "Apple, Banana, Kiwi";var res = str.slice(-12,-6);The result of res will be: Banana --><p>The slice() method extract a part of a stringand returns the extracted parts in a new string:</p><p id="demo"></p><script>var str = "Apple, Banana, Kiwi";document.getElementById("demo").innerHTML = str.slice(-12,-6);</script><!-- result: banana --><!-- If you omit the second parameter, the method will slice out the rest of the string:Examplevar res = str.slice(7); --><p>The slice() method extract a part of a stringand returns the extracted parts in a new string:</p><p id="demo"></p><script>var str = "Apple, Banana, Kiwi";document.getElementById("demo").innerHTML = str.slice(7);</script><!-- result: Banana, Kiwi --><!-- or, counting from the end:Examplevar res = str.slice(-12); --><p>The slice() method extract a part of a stringand returns the extracted parts in a new string:</p><p id="demo"></p><script>var str = "Apple, Banana, Kiwi";document.getElementById("demo").innerHTML = str.slice(-12);</script><!-- Banana, Kiwi --><!-- Note Negative positions does not work in Internet Explorer 8 and earlier. -->

<!-- b) The substring() Methodsubstring() is similar to slice().The difference is that substring() cannot accept negative indexes.Examplevar str = "Apple, Banana, Kiwi";var res = str.substring(7,13);The result of res will be: Banana --><p>The substr() method extract a part of a stringand returns the extracted parts in a new string:</p><p id="demo"></p><script>var str = "Apple, Banana, Kiwi";document.getElementById("demo").innerHTML = str.substring(7,13);</script><!-- Banana ---><!-- If you omit the second parameter, substring() will slice out the rest of the string. -->

<!-- c) The substr() Methodsubstr() is similar to slice().The difference is that the second parameter specifies the length of the extracted part.Example

Javascript-Tutorial 30 von 46 Quelle: www.w3schools.com

Page 31:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var str = "Apple, Banana, Kiwi";var res = str.substr(7,6);The result of res will be: Banana --><p>The substr() method extract a part of a stringand returns the extracted parts in a new string:</p><p id="demo"></p><script>var str = "Apple, Banana, Kiwi";document.getElementById("demo").innerHTML = str.substr(7,6);</script><!-- If the first parameter is negative, the position counts from the end of the string.The second parameter can not be negative, because it defines the length.If you omit the second parameter, substr() will slice out the rest of the string. -->

<!-- 90. Replacing String ContentThe replace() method replaces a specified value with another value in a string:Examplestr = "Please visit Microsoft!";var n = str.replace("Microsoft","W3Schools"); --><p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p><button onclick="myFunction()">Try it</button><p id="demo">Please visit Microsoft!</p><script>function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace("Microsoft","W3Schools"); document.getElementById("demo").innerHTML = txt;}</script><!-- The replace() method can also take a regular expression as the search value.

91. Converting to Upper and Lower CaseA string is converted to upper case with toUpperCase():Examplevar text1 = "Hello World!"; // Stringvar text2 = text1.toUpperCase(); // text2 is text1 converted to upper --><p>Convert string to upper case:</p><button onclick="myFunction()">Try it</button><p id="demo">Hello World!</p><script>function myFunction() { var text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.toUpperCase();}</script>HELLO WORLD!<!-- A string is converted to lower case with toLowerCase():Examplevar text1 = "Hello World!"; // Stringvar text2 = text1.toLowerCase(); // text2 is text1 converted to lower --><p>Convert string to lower case:</p><button onclick="myFunction()">Try it</button><p id="demo">Hello World!</p><script>function myFunction() { var text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.toLowerCase();}</script>hello world!

<!-- 92. The concat() Methodconcat() joins two or more strings:Examplevar text1 = "Hello";var text2 = "World";

Javascript-Tutorial 31 von 46 Quelle: www.w3schools.com

Page 32:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

text3 = text1.concat(" ",text2); --><p>The concat() method joins two or more strings:</p><p id="demo"></p><script>var text1 = "Hello";var text2 = "World!"document.getElementById("demo").innerHTML = text1.concat(" ",text2);</script>Hello World!<!-- All string methods return a new string. They don't modify the original string.Formally said: Strings are immutable: Strings cannot be changed, only replaced.

93. Extracting String CharactersThere are 2 safe methods for extracting string characters:charAt(position)charCodeAt(position)

a) The charAt() MethodThe charAt() method returns the character at a specified index (position) in a string:Examplevar str = "HELLO WORLD";str.charAt(0); // returns H --><p>The charAt() method returns the character at a given position in a string:</p><p id="demo"></p><script>var str = "HELLO WORLD";document.getElementById("demo").innerHTML = str.charAt(0);</script>H (is at position 0)

<!-- b) The charCodeAt() MethodThe charCodeAt() method returns the unicode of the character at a specified index in a string:Examplevar str = "HELLO WORLD";str.charCodeAt(0); // returns 72 --><p>The charCodeAt() method returns the unicode of the character at a given position in a string:</p><p id="demo"></p><script>var str = "HELLO WORLD";document.getElementById("demo").innerHTML = str.charCodeAt(0);</script>

<!-- 94. Accessing a String as an Array is UnsafeYou might have seen code like this, accessing a string as an array:var str = "HELLO WORLD";str[0]; // returns HThis 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)If you want to read a string as an array, convert it to an array first. -->

<!-- 95. Converting a String to an ArrayA string can be converted to an array with the split() method:Examplevar txt = "a,b,c,d,e"; // Stringtxt.split(","); // Split on commastxt.split(" "); // Split on spacestxt.split("|"); // Split on pipe --><p>Click "Try it" to display the first array element, after a string split.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var str = "a,b,c,d,e,f"; var arr = str.split(",");

Javascript-Tutorial 32 von 46 Quelle: www.w3schools.com

Page 33:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

document.getElementById("demo").innerHTML = arr[0];}</script>result: a<!-- If the separator is omitted, the returned array will contain the whole string in index [0].If the separator is "", the returned array will be an array of single characters:Examplevar txt = "Hello"; // Stringtxt.split(""); // Split in characters --><p id="demo"></p><script>var str = "Hello";var arr = str.split("");var text = "";var i;for (i = 0; i < arr.length; i++) { text += arr[i] + "<br>"}document.getElementById("demo").innerHTML = text;</script>result: Hello<!-- Complete String ReferenceFor a complete reference, go to our Complete JavaScript String Reference.The reference contains descriptions and examples of all string properties and methods. -->

<!-- exercise 1: Display the position of the first occurrence of "World" in the variable txt.Hint: Use the indexOf() method. --><p id="demo"></p><script>var txt = "Hello World";document.getElementById("demo").innerHTML = txt;</script>Hello World<!-- answer: --><p id="demo"></p><script>var txt = "Hello World";document.getElementById("demo").innerHTML = txt.indexOf("World");</script>6

<!-- Exercise 2: Use the slice() method to display only "Banana,Kiwi". --><p id="demo"></p><script>var str = "Apple,Banana,Kiwi";document.getElementById("demo").innerHTML = str;</script><!-- answer: --><p id="demo"></p><script>var str = "Apple,Banana,Kiwi";document.getElementById("demo").innerHTML = str.slice(6);</script>

<!-- Exercise 3: Use the replace() method to replace the word "World", in the variable txt, with "Universe". --><p id="demo"></p><script>var txt = "Hello World";document.getElementById("demo").innerHTML = txt;</script><!-- answer: --><p id="demo"></p><script>

Javascript-Tutorial 33 von 46 Quelle: www.w3schools.com

Page 34:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var txt = "Hello World";document.getElementById("demo").innerHTML = txt.replace("World", "Universe");</script>Hello World --> Hello Universe

<!-- Exercise 4: Convert the value of txt to upper case. Hint: Use the toUpperCase() method. --><p id="demo"></p><script>var txt = "Hello World";document.getElementById("demo").innerHTML = txt;</script><!-- answer: --><p id="demo"></p><script>var txt = "Hello World";document.getElementById("demo").innerHTML = txt.toUpperCase();</script>HELLO WORLD

<!-- Exercise 5: Use the concat() method to join the two strings: str1 and str2. --><p id="demo">Display the result here.</p><script>var str1 = "Hello ";var str2 = "World!";</script><!-- answer: --><p id="demo">Display the result here.</p><script>var str1 = "Hello ";var str2 = "World!";document.getElementById("demo").innerHTML = str1.concat(str2);</script>

<!-- 96. JavaScript Numbers --><!-- a) JavaScript has only one type of number.Numbers can be written with, or without, decimals.JavaScript numbers can be written with, or without decimals:Examplevar x = 34.00; // A number with decimalsvar y = 34; // A number without decimalsExtra large or extra small numbers can be written with scientific (exponent) notation:Examplevar x = 123e5; // 12300000var y = 123e-5; // 0.00123 -->

<!-- b) JavaScript Numbers are Always 64-bit Floating PointUnlike 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. This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:Value (aka Fraction/Mantissa) Exponent Sign52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63) -->

<!-- c) PrecisionIntegers (numbers without a period or exponent notation) are considered accurate up to 15 digits.Examplevar x = 999999999999999; // x will be 999999999999999var y = 9999999999999999; // y will be 10000000000000000 --><p>Integers are considered accurate up to 15 digits.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var x = 999999999999999; var y = 9999999999999999;

Javascript-Tutorial 34 von 46 Quelle: www.w3schools.com

Page 35:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

document.getElementById("demo").innerHTML = x + "<br>" + y;}</script>

<!-- d) The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:Examplevar x = 0.2 + 0.1; // x will be 0.30000000000000004 --><!-- To solve the problem above, it helps to multiply and divide:Examplevar x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3 --><p>Floating point arithmetic is not always 100% accurate.</p><p>But it helps to multiply and divide.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var x = (0.2*10 + 0.1*10) / 10; document.getElementById("demo").innerHTML = "0.2 + 0.1 = " + x;}</script>0.2 + 0.1 = 0.3

<!-- e) Hexadecimal: JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.Examplevar x = 0xFF; // x will be 255 --><p>Numeric constants, preceded by 0x, are interpreted as hexadecimal.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = "0xFF = " + 0xFF;}</script>0xFF = 255<!-- Note:Never write a number with a leading zero (like 07).Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

By default, Javascript displays numbers as base 10 decimals.But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).Examplevar myNumber = 128;myNumber.toString(16); // returns 80myNumber.toString(8); // returns 200myNumber.toString(2); // returns 10000000 --><p>The toString() method can output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).</p><p id="demo"></p><button onclick="myFunction()">Try it</button><script>function myFunction() { var myNumber = 128; document.getElementById("demo").innerHTML = "128 = " + myNumber + " Decimal, " + myNumber.toString(16) + " Hexadecimal, " + myNumber.toString(8) + " Octal, " + myNumber.toString(2) + " Binary."}</script>128 = 128 Decimal, 80 Hexadecimal, 200 Octal, 10000000 Binary.

<!-- f) Infinity: Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.Examplevar myNumber = 2;while (myNumber != Infinity) { // Execute until Infinity myNumber = myNumber * myNumber;} --><p>Infinity is returned if you calculate a number outside the largest possible number.</p><button onclick="myFunction()">Try it</button><p id="demo"></p>

Javascript-Tutorial 35 von 46 Quelle: www.w3schools.com

Page 36:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<script>function myFunction() { var myNumber = 2; var txt = ""; while (myNumber != Infinity) { myNumber = myNumber * myNumber; txt = txt + myNumber + "<br>"; } document.getElementById("demo").innerHTML = txt;}</script>416256655364294967296184467440737095520003.402823669209385e+381.157920892373162e+771.3407807929942597e+154Infinity<p>Division by zero also generates Infinity.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var x = 2/0; var y = -2/0; document.getElementById("demo").innerHTML = x + "<br>" + y;}</script>Infinity-Infinity<p>Infinity is a Number.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = typeof Infinity;}</script>number<!-- g) NaN - Not a NumberNaN is a JavaScript reserved word indicating that a value is not a number.Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):Examplevar x = 100 / "Apple"; // x will be NaN (Not a Number) --><!-- However, if the string contains a numeric value , the result will be a number:Examplevar x = 100 / "10"; // x will be 10 --><!-- You can use the global JavaScript function isNaN() to find out if a value is a number.Examplevar x = 100 / "Apple";isNaN(x); // returns true because x is Not a Number --><p id="demo"></p><script>var x = 100 / "Apple";document.getElementById("demo").innerHTML = isNaN(x);</script>true<!-- Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN.Examplevar x = NaN;var y = 5;var z = x + y; // z will be NaN --><!-- NaN is a number: typeOf NaN returns number.Example

Javascript-Tutorial 36 von 46 Quelle: www.w3schools.com

Page 37:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

typeof NaN; // returns "number" --><!-- h) Numbers Can be ObjectsNormally JavaScript numbers are primitive values created from literals: var x = 123But numbers can also be defined as objects with the keyword new: var y = new Number(123)Examplevar x = 123;var y = new Number(123);typeof x; // returns numbertypeof y; // returns object --><p id="demo"></p><script>var x = 123;var y = new Number(123);document.getElementById("demo").innerHTML = typeof x + "<br>" + typeof y;</script>numberobject<!-- Don't create Number objects. They slow down execution speed, and produce nasty side effects:Examplevar x = 123; var y = new Number(123);(x === y) // is false because x is a number and y is an object. -->

<!-- i) Number Properties and MethodsPrimitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.Number PropertiesProperty DescriptionMAX_VALUE Returns the largest number possible in JavaScriptMIN_VALUE Returns the smallest number possible in JavaScriptNEGATIVE_INFINITY Represents negative infinity (returned on overflow)NaN Represents a "Not-a-Number" valuePOSITIVE_INFINITY Represents infinity (returned on overflow)Examplevar x = Number.MAX_VALUE; --><p id="demo"></p><script>document.getElementById("demo").innerHTML = Number.MAX_VALUE;</script>1.7976931348623157e+308<!-- j) Number properties belongs to the JavaScript's number object wrapper called Number.These properties can only be accessed as Number.MAX_VALUE.Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:Examplevar x = 6;var y = x.MAX_VALUE; // y becomes undefined --><!-- Number methods are covered in the next chapter -->

<!-- Exercise 1: Create a variable called number, assign the value 50 to it, and display it.Hint: Remember that, unlike strings, numbers are written without quotes. --><p id="demo">Display the result here.</p> <script>// Create the variable here</script><!-- answer --><script>var number = 50;document.getElementById("demo").innerHTML = number;</script>

<!-- exercise 2: The value of the variable z should be 11, find out what's wrong and fix it.Hint: If you put quotes around a number, it will be treated as a text string. --><p id="demo"></p> <script>var x = 5;var y = "6";

Javascript-Tutorial 37 von 46 Quelle: www.w3schools.com

Page 38:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var z = x + y;document.getElementById("demo").innerHTML = z;</script>56<!-- answer --><script>var x = 5;var y = 6;var z = x + y;document.getElementById("demo").innerHTML = z;</script>

<!-- exercise 3: Divide the variable number by 3. Hint: Use the division operator (/) to divide a value. --><p id="demo"></p> <script>var number = 50;document.getElementById("demo").innerHTML = number;</script><!-- answer --><script>var number = 50 / 3;document.getElementById("demo").innerHTML = number;</script>16.666666666666668

<!-- exercise 4: Display the sum of 8 * 5, using two variables x and y. Hint: Use the multiplication operator (*) to multiply values. --><p id="demo">Display the result here.</p> <script>// Create the variables here</script><!-- answer --><script>var x = 8;var y = 5;document.getElementById("demo").innerHTML = x * y;</script>40

<!-- 97. JavaScript Number Methods: Number methods help you to work with numbers.--><!-- a) Global MethodsJavaScript global functions can be used on all JavaScript data types.These are the most relevant methods, when working with numbers:Method DescriptionNumber() Returns a number, converted from its argument.parseFloat() Parses its argument and returns a floating point numberparseInt() Parses its argument and returns an integer -->

<!-- b) Number MethodsJavaScript number methods are methods that can be used on numbers:Method DescriptiontoString() Returns a number as a stringtoExponential() Returns a string, with a number rounded and written using exponential notation.toFixed() Returns a string, with a number rounded and written with a specified number of decimals.toPrecision() Returns a string, with a number written with a specified lengthvalueOf() Returns a number as a numberNote: All number methods return a new variable. They do not change the original variable. -->

<!-- c) The toString() MethodtoString() returns a number as a string.All number methods can be used on any type of numbers (literals, variables, or expressions):Examplevar x = 123;x.toString(); // returns 123 from variable x(123).toString(); // returns 123 from literal 123(100 + 23).toString(); // returns 123 from expression 100 + 23 --><p>The toString() method converts a number to a string.</p><p id="demo"></p><script>var x = 123;document.getElementById("demo").innerHTML =

Javascript-Tutorial 38 von 46 Quelle: www.w3schools.com

Page 39:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

x.toString() + "<br>" + (123).toString() + "<br>" + (100 + 23).toString();�</script>

<!-- d) The toExponential() MethodtoExponential() returns a string, with a number rounded and written using exponential notation.A parameter defines the number of character behind the decimal point:Examplevar x = 9.656;x.toExponential(2); // returns 9.66e+0x.toExponential(4); // returns 9.6560e+0x.toExponential(6); // returns 9.656000e+0 --><p>The toExponential() method returns a string, with the number rounded and written using exponential notation.</p><p>An optional parameter defines the number of digits behind the decimal point.</p><p id="demo"></p><script>var x = 9.656;document.getElementById("demo").innerHTML = x.toExponential() + "<br>" + x.toExponential(2) + "<br>" + x.toExponential(4) + "<br>" + x.toExponential(6);</script>9.656e+09.66e+09.6560e+09.656000e+0<!-- The parameter is optional. If you don't specify it, JavaScript will not round the number. -->

<!-- e) The toFixed() MethodtoFixed() returns a string, with the number written with a specified number of decimals:Examplevar x = 9.656;x.toFixed(0); // returns 10x.toFixed(2); // returns 9.66x.toFixed(4); // returns 9.6560x.toFixed(6); // returns 9.656000 --><!-- Note:toFixed(2) is perfect for working with money. --><p>The toFixed() method rounds a number to a given number of digits.</p><p>For working with money, toFixed(2) is perfect.</p><p id="demo"></p><script>var x = 9.656;document.getElementById("demo").innerHTML = x.toFixed(0) + "<br>" + x.toFixed(2) + "<br>" + x.toFixed(4) + "<br>" + x.toFixed(6);</script>109.669.65609.656000

<!-- f) The toPrecision() MethodtoPrecision() returns a string, with a number written with a specified length:Examplevar x = 9.656;x.toPrecision(); // returns 9.656x.toPrecision(2); // returns 9.7x.toPrecision(4); // returns 9.656x.toPrecision(6); // returns 9.65600 --><p>The toPrecision() method returns a string, with a number written with a specified length:</p><p id="demo"></p><script>

Javascript-Tutorial 39 von 46 Quelle: www.w3schools.com

Page 40:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

var x = 9.656;document.getElementById("demo").innerHTML = x.toPrecision() + "<br>" + x.toPrecision(2) + "<br>" + x.toPrecision(4) + "<br>" + x.toPrecision(6); </script>9.6569.79.6569.65600

<!-- 98. Converting Variables to NumbersThere are 3 JavaScript functions that can be used to convert variables to numbers:The Number() methodThe parseInt() methodThe parseFloat() methodThese methods are not number methods, but global JavaScript methods. -->

<!-- a) The Number() MethodNumber(), can be used to convert JavaScript variables to numbers:Examplex = true;Number(x); // returns 1x = false; Number(x); // returns 0x = new Date();Number(x); // returns 1404568027739x = "10"Number(x); // returns 10x = "10 20"Number(x); // returns NaN --><p>The global JavaScript function Number() converts variables to numbers:</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = Number(true) + "<br>" + Number(false) + "<br>" + Number(new Date()) + "<br>" + Number(" 10") + "<br>" + Number("10 ") + "<br>" + Number("10 6"); </script>1014251509223691010NaN

<!-- b) The parseInt() MethodparseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:ExampleparseInt("10"); // returns 10parseInt("10.33"); // returns 10parseInt("10 20 30"); // returns 10parseInt("10 years"); // returns 10parseInt("years 10"); // returns NaN If the number cannot be converted, NaN (Not a Number) is returned.--><p>The global JavaScript function parseInt() converts strings to numbers:</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = parseInt("10") + "<br>" + parseInt("10.33") + "<br>" + parseInt("10 6") + "<br>" +

Javascript-Tutorial 40 von 46 Quelle: www.w3schools.com

Page 41:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

parseInt("10 years") + "<br>" + parseInt("years 10"); </script>10101010NaN

<!-- c) The parseFloat() MethodparseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:ExampleparseFloat("10"); // returns 10parseFloat("10.33"); // returns 10.33parseFloat("10 20 30"); // returns 10parseFloat("10 years"); // returns 10parseFloat("years 10"); // returns NaN --><p>The global JavaScript function parseFloat() converts strings to numbers:</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = parseFloat("10") + "<br>" + parseFloat("10.33") + "<br>" + parseFloat("10 6") + "<br>" + parseFloat("10 years") + "<br>" + parseFloat("years 10"); </script>1010.331010NaN

<!-- d) The valueOf() MethodvalueOf() returns a number as a number.Examplevar x = 123;x.valueOf(); // returns 123 from variable x(123).valueOf(); // returns 123 from literal 123(100 + 23).valueOf(); // returns 123 from expression 100 + 23 --><p id="demo"></p><script>var x = 123;document.getElementById("demo").innerHTML = x.valueOf() + "<br>" + (123).valueOf() + "<br>" + (100 + 23).valueOf();</script>123123123<!-- In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.There is no reason to use it in your code.Note: In JavaScript, all data types have a valueOf() and a toString() method.For a complete reference, go to our Complete JavaScript Number Reference.The reference contains descriptions and examples of all Number properties and methods. -->

<!-- 99. JavaScript Math ObjectThe Math object allows you to perform mathematical tasks.The Math object includes several mathematical methods.

a) One common use of the Math object is to create a random number:ExampleMath.random(); // returns a random number --><p>Math.random() returns a random number between 0 and 1.</p><button onclick="myFunction()">Try it</button>

Javascript-Tutorial 41 von 46 Quelle: www.w3schools.com

Page 42:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.random();}</script><!-- Math has no constructor. No methods have to create a Math object first.

b) Math.min() and Math.max()Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:ExampleMath.min(0, 150, 30, 20, -8); // returns -8 --><p>Math.min() returns the lowest value.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.min(0, 150, 30, 20, -5);}</script>-5

<p>Math.max() returns the highest value.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.max(0, 150, 30, 20, -8);}</script>150

<!-- c) Math.round()Math.round() rounds a number to the nearest integer:ExampleMath.round(4.7); // returns 5Math.round(4.4); // returns 4 --><p>Math.round() rounds a number to its nearest integer.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.round(4.4);}</script>

<!-- d) Math.ceil()Math.ceil() rounds a number up to the nearest integer:ExampleMath.ceil(4.4); // returns 5 --><p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.ceil(4.4);}</script>5

<!-- e) Math.floor()Math.floor() rounds a number down to the nearest integer:ExampleMath.floor(4.7); // returns 4 --><p>Math.floor() rounds a number <strong>down</strong> to its nearest integer.</p>

Javascript-Tutorial 42 von 46 Quelle: www.w3schools.com

Page 43:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.floor(4.7);}</script>4

<!-- f) Math.floor() and Math.random() can be used together to return a random number between 0 and 10:ExampleMath.floor(Math.random() * 11); // returns a random number between 0 and 10 --><p>Math.floor() combined with Math.random() can return random integers.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.floor(Math.random() * 11);}</script>0 - 10

<!-- g) Math ConstantsJavaScript provides 8 mathematical constants that can be accessed with the Math object:ExampleMath.E; // returns Euler's numberMath.PI // returns PIMath.SQRT2 // returns the square root of 2Math.SQRT1_2 // returns the square root of 1/2Math.LN2 // returns the natural logarithm of 2Math.LN10 // returns the natural logarithm of 10Math.LOG2E // returns base 2 logarithm of EMath.LOG10E // returns base 10 logarithm of E --><p>Math constants are E, PI, SQR2, SQR1_2, LN2, LN10, LOG2E, LOG10E</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { document.getElementById("demo").innerHTML = Math.E + "<br>" + Math.PI + "<br>" + Math.SQRT2 + "<br>" + Math.SQRT1_2 + "<br>" + Math.LN2 + "<br>" + Math.LN10 + "<br>" + Math.LOG2E + "<br>" + Math.LOG10E + "<br>";}</script>2.7182818284590453.1415926535897931.41421356237309510.70710678118654760.69314718055994532.3025850929940461.44269504088896340.4342944819032518

<!-- h) Math Object MethodsMethod Descriptionabs(x) Returns the absolute value of xacos(x) Returns the arccosine of x, in radiansasin(x) Returns the arcsine of x, in radiansatan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radiansatan2(y,x) Returns the arctangent of the quotient of its arguments

Javascript-Tutorial 43 von 46 Quelle: www.w3schools.com

Page 44:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

ceil(x) Returns x, rounded upwards to the nearest integercos(x) Returns the cosine of x (x is in radians)exp(x) Returns the value of Exfloor(x) Returns x, rounded downwards to the nearest integerlog(x) Returns the natural logarithm (base E) of xmax(x,y,z,...,n) Returns the number with the highest valuemin(x,y,z,...,n) Returns the number with the lowest valuepow(x,y) Returns the value of x to the power of yrandom() Returns a random number between 0 and 1round(x) Rounds x to the nearest integersin(x) Returns the sine of x (x is in radians)sqrt(x) Returns the square root of xtan(x) Returns the tangent of an angle -->

<!-- Complete Math ReferenceFor a complete reference, go to our complete Math object reference.The reference contains descriptions and examples of all Math properties and methods. -->

<!-- 100. JavaScript DatesThe Date object lets you work with dates (years, months, days, minutes, seconds, milliseconds)

a) Displaying DatesIn this tutorial we use a script to display dates inside a <p> element with id="demo":Example<p id="demo"></p><script>document.getElementById("demo").innerHTML = Date();</script> --><p id="demo"></p><script>document.getElementById("demo").innerHTML = Date();</script>Sun Mar 01 2015 09:26:39 GMT+0100 (Mitteleuropäische Zeit)<!-- The script above says: assign the value of Date() to the content (innerHTML) of the element with id="demo". Note: You will learn how to display a date, in a more readable format, at the bottom of this page.

b) Creating Date ObjectsThe Date object lets us work with dates.A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.Date objects are created with the new Date() constructor.There are 4 ways of initiating a date:

new Date()new Date(milliseconds)new Date(dateString)new Date(year, month, day, hours, minutes, seconds, milliseconds)Using new Date(), creates a new date object with the current date and time:

Example<script>var d = new Date();document.getElementById("demo").innerHTML = d;</script> --><p id="demo"></p><script>var d = new Date();document.getElementById("demo").innerHTML = d;</script>Sun Mar 01 2015 09:29:18 GMT+0100 (Mitteleuropäische Zeit)<!-- Using new Date(date string), creates a new date object from the specified date and time:Example<script>var d = new Date("October 13, 2014 11:13:00");document.getElementById("demo").innerHTML = d;</script> --><p id="demo"></p>

Javascript-Tutorial 44 von 46 Quelle: www.w3schools.com

Page 45:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

<script>var d = new Date("October 13, 2014 11:13:00");document.getElementById("demo").innerHTML = d;</script>Mon Oct 13 2014 11:13:00 GMT+0200 (Mitteleuropäische Sommerzeit)<!-- Using new Date(number), creates a new date object as zero time plus the number.Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds:Example<script>var d = new Date(86400000);document.getElementById("demo").innerHTML = d;</script> --><p id="demo"></p><script>var d = new Date(86400000);document.getElementById("demo").innerHTML = d;</script>Fri Jan 02 1970 01:00:00 GMT+0100 (Mitteleuropäische Zeit)<!-- Note:JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC).One day contains 86,400,000 millisecond.Using new Date(7 numbers), creates a new date object with the specified date and time:The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order:Example<script>var d = new Date(99,5,24,11,33,30,0);document.getElementById("demo").innerHTML = d;</script> --><p id="demo"></p><script>var d = new Date(99,5,24,11,33,30,0);document.getElementById("demo").innerHTML = d;</script>Thu Jun 24 1999 11:33:30 GMT+0200 (Mitteleuropäische Sommerzeit)<!-- Variants of the example above let us omit any of the last 4 parameters:Example<script>var d = new Date(99,5,24);document.getElementById("demo").innerHTML = d;</script> --><!-- Note:JavaScript counts months from 0 to 11. January is 0. December is 11. -->

<!-- c) Date MethodsWhen a Date object is created, a number of methods allow you to operate on it.Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects,using either local time or UTC (universal, or GMT) time.The next chapter, of this tutorial, covers the date object's methods.

d) Displaying DatesWhen you display a date object in HTML, it is automatically converted to a string, with the toString() method.Example<p id="demo"></p><script>d = new Date();document.getElementById("demo").innerHTML = d;</script>Is the same as:<p id="demo"></p><script>d = new Date();document.getElementById("demo").innerHTML = d.toString();</script> --><p id="demo"></p><script>var d = new Date();document.getElementById("demo").innerHTML = d.toString();</script>Sun Mar 01 2015 09:44:18 GMT+0100 (Mitteleuropäische Zeit)<!-- The toUTCString() method converts a date to a UTC string (a date display standard).

Javascript-Tutorial 45 von 46 Quelle: www.w3schools.com

Page 46:  · An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected

Example<script>var d = new Date();document.getElementById("demo").innerHTML = d.toUTCString();</script> --><p>The toUTCString() method converts a date to a UTC string (date display standard).</p><p id="demo"></p><script>var d = new Date();document.getElementById("demo").innerHTML = d.toUTCString();</script>The toUTCString() method converts a date to a UTC string (date display standard).Sun, 01 Mar 2015 08:45:29 GMT<!-- The toDateString() method converts a date to a more readable format:Example<script>var d = new Date();document.getElementById("demo").innerHTML = d.toDateString();</script> --><p id="demo"></p><script>var d = new Date();document.getElementById("demo").innerHTML = d.toDateString();</script>Sun Mar 01 2015<!-- Note:Date objects are static, not dynamic. The computer time is ticking, but date objects, once created, are not. -->

</body></html>

Javascript-Tutorial 46 von 46 Quelle: www.w3schools.com