Showing posts with label JavaScript Working. Show all posts
Showing posts with label JavaScript Working. Show all posts

Monday, August 27, 2012

JavaScript Working


A JavaScript can be put in the <body> and in the <head> section of an HTML page.

JavaScript in <body>

The example below manipulate the content of an existing <p> element when the page loads:

Example

<!DOCTYPE html>
<html>
<body><h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>

</body>
</html>

Try it yourself »

lampThe JavaScript is placed at the bottom of the page to make sure it is executed after the <p> element is created.


JavaScript Functions and Events

The JavaScript statement in the example above, is executed when the page loads, but that is not always what we want.

Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. Then we can write the script inside a function, and call the function when the event occurs.

You will learn more about JavaScript functions and events in later chapters.

A JavaScript Function in <head>

The example below calls a function in the <head> section when a button is clicked:

Example

<!DOCTYPE html>
<html><head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</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 »


A JavaScript Function in <body>

This example also calls a function when a button is clicked, but the function is in the <body>:

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="My First JavaScript Function";
}
</script>

</body>
</html>

Try it yourself »


Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, and you can have scripts in both the <body> and the <head> section at the same time.

It is a common practice to put functions in the <head> section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

Using an External JavaScript

Scripts can also be placed in external files. External files often contain code to be used by several different web pages.

External JavaScript files have the file extension .js.
To use an external script, point to the .js file in the "src" attribute of the <script> tag:

Example

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

Try it yourself »

You can place the script in the <head> or <body> as you like. The script will behave as it was located exactly where you put the <script> tag in the document.

lampExternal scripts cannot contain <script> tags.