Sunteți pe pagina 1din 9

JavaScript

JavaScript is the programming language of the Web.

All modern HTML pages are using JavaScript.

JavaScript is easy to learn.

Why Study JavaScript?

JavaScript is one of 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

This tutorial is about JavaScript, and how JavaScript works with HTML and CSS.

JavaScript Introduction
« Previous
Next Chapter »

JavaScript is the most popular programming language in the world.

It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart phones, and more.

This page contains some examples of what JavaScript can do in HTML.


JavaScript Can Change HTML Elements

The HTML DOM (the Document Object Model) is the official W3C standard for accessing HTML elements.

JavaScript can manipulate the DOM (change HTML contents).

The following example changes the content (innerHTML) of an HTML element identified with id="demo":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";

Try it Yourself »

The method document.getElementById() is one of many methods in the HTML DOM.

You can use JavaScript to:

Change HTML elements


Delete HTML elements
Create new HTML elements
Copy and clone HTML elements
And much more ...

There are several chapters, about the HTML DOM, later in this tutorial.
JavaScript Can Change HTML Attributes

This example changes the value of the source attribute (src) of an HTML <img> element:
The Light bulb

Click the light bulb to turn on/off the light


Try it Yourself »

With JavaScript, you can change almost any HTML attribute.


JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute.


Example
document.getElementById("demo").style.fontSize = "25px";

Try it Yourself »

With JavaScript, you can change almost any CSS value.


JavaScript Can Validate Data

JavaScript is often used to validate input:

Please input a number between 1 and 10

Try it Yourself »

Did You Know?


Note JavaScript and Java are different languages, both in concept and design.

JavaScript was invented by Brendan Eich, to be used in Netscape (a no longer existing browser) in 1995,
and was adopted by the ECMA standard association in 1997.

ECMA-262 is the official name. ECMAScript 5 (version 1.8.5 - July 2010) is the latest standard.

JavaScript Where To
« Previous
Next Chapter »

In HTML, JavaScripts must be inserted between <script> and </script> tags.

JavaScripts can be put in the <body> and in the <head> section of an HTML page.
The <script> Tag

To insert a JavaScript into an HTML page, use the <script> tag.

The <script> and </script> tells where the JavaScript starts and ends.

The lines between <script> and </script> contain the JavaScript code:
Example
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "My First JavaScript Function";
}
</script>

You don't have to understand the code above.


Just take it for a fact, that the browser will interpret the code as JavaScript.
Note Old examples may have type="text/javascript" in the <script> tag. This is no longer required.
JavaScript is the default scripting language in all modern browsers, and in HTML5.

JavaScript Functions and Events

Often, JavaScript code is written to be executed when an event occurs, like when the user clicks a button.

JavaScript code inside a function, can be invoked, when an event occurs.

Invoke a function = call upon a function (ask for the code in the function to be executed).

You will learn much more about functions and events in later chapters.
JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

Often you will see scripts at the bottom of the <body> section. This can reduce display time.

Sometimes you will see all JavaScript functions in the <head> section.

Anyway, separating HTML and JavaScript, and putting all code in one place, is always a good habit.
JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is invoked (called) when a button is clicked:


Example
<!DOCTYPE html>
<html>

<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>

<body>

<h1>My Web Page</h1>

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

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

Try it Yourself »

JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</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>
</html>

Try it Yourself »

Note It is a good idea to place scripts at the bottom of the <body> element.
This improves page load, because HTML loading is not blocked by scripts loading.

External JavaScripts

Scripts can also be placed in external files.

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the source (src) attribute of the <script> tag:
Example
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

Try it Yourself »

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where you put the reference in the HTML document.
Note External scripts cannot contain <script> tags.

External JavaScript Advantages


Placing JavaScripts in external files has some advantages:

It separates HTML and code.


It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads.
JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).


Example
<!DOCTYPE html>
<html>
<body>

<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>

</body>
</html>

Try it Yourself »

JavaScript Function Syntax

A 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.

Function Invocation

The 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.
Function Return

When 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":
Example

Calculate the product of two numbers, and return the result:


var x = myFunction(4, 3); // Function is called, return value will end up in x

function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}

The result in x will be:


12

Try it Yourself »

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.
Example

Convert Fahrenheit to Celsius:


<!DOCTYPE html>
<html>
<body>

<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(77);
</script>

</body>
</html>

Using the example above, toCelcius() refers to the function result.


Example
JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box

An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");

The window.alert method can be written without the window prefix.


Example
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box:</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("I am an alert box!");
}
</script>

</body>
</html>

Try it Yourself »

Confirm Box

A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax
window.confirm("sometext");

The window.confirm() method can be written without the window prefix.


Example
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a confirm box.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

Try it Yourself »

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
window.prompt("sometext","defaultText");

The window.prompt() method can be written without the window prefix.


Example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");

if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
</script>

</body>
</html>

Try it Yourself »

Line Breaks

To display line breaks inside a popup box, use a back-slash followed by the character n.
Example
<!DOCTYPE html>
<html>
<body>

<p>Click the button to demonstrate line-breaks in a popup box.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("Hello\nHow are you?");
}
</script>

</body>
</html>

Try it Yourself »

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