Showing posts with label JavaScript: How to Use. Show all posts
Showing posts with label JavaScript: How to Use. Show all posts

Monday, August 27, 2012

JavaScript: How to Use


A JavaScript is surrounded by a <script> and </script> tag.
JavaScript is typically used to manipulate HTML elements.

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 the <script> and </script> contain the JavaScript:

<script>
alert("My First JavaScript");
</script>

You don't have to understand the code above. Just take it for a fact, that the browser will interpret and execute the JavaScript code between the <script> and </script> tags.

lampSome examples have type="text/javascript" in the <script> tag. This is not required in HTML5. JavaScript is the default scripting language in all modern browsers and in HTML5.


Manipulating HTML Elements

To access an HTML element from a JavaScript, use the document.getElementById(id) method, and an "id" attribute to identify the HTML element:

Example

Access the HTML element with the specified id, and change its content:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph</p>

<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>


</body>
</html>

Try it yourself »

The JavaScript is executed by the web browser. In this case, the browser will access the HTML element with id="demo", and replace its content (innerHTML) with "My First JavaScript".

Writing Directly into The Document Output

The example below writes a <p> element directly into the HTML document output:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
document.write("<p>My First JavaScript</p>");
</script>


</body>
</html>

Try it yourself »


Warning

Use document.write() only to write directly into the document output.
If you execute document.write after the document has finished loading, the entire HTML page will be overwritten:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p>My First Paragraph.</p>

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

<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>


</body>
</html>

Try it yourself »