Tutorials

Learn web design and programming with our free video and text tutorials.

How To Embed Javascript within an (X)HTML File

The <script> tag is used to embed javascript within an (X)HTML file and accepts the "type" and "language" attributes each with a value of "javascript". Javascript can be included within the <head> and/or <body> sections.

Javascript that is placed in teh <head> section will be executed when it is called.

Javascript that is placed in the <body> section will be executed while the web page loads.

An (X)HTML file can include as many javascript <script> tags as you like. You can also specify a javascript version, which you can learn about later.

The javascript code below shows you how to write a simple statement using javascript.

<script type="text/javascript" language="javascript">

document.write("Hello World!");

</script>

Include the code above within your (X)HTML file within the <body> tags, like below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>
</head>
<body>

<script type="text/javascript" language="javascript">

document.write("Hello World!");

</script>

</body>
</html>

The code above will display the text "Hello World!" in your web browser. The text that is produces will appear like the text below.

Hello World!

You can also include (X)HTML tags within your javascript code.

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>
</head>
<body>

<script type="text/javascript" language="javascript">

document.write("<h1>Hello World!</h1>");

</script>

</body>
</html>

The javascript code above produces the level 1 heading below.

Hello World!

The javascript code below shows you how to include javascript within the <head> tag.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>

<script type="text/javascript" language="javascript">

function popup() {alert("Hello World")}

</script>

</head>
<body>

<input type="button" onclick="popup()" value="Click Here" />

</body>
</html>

The javascript and (X)HTML code above produces the button below. When the button is clicked (this is called an event), an alert will pop up with the text "Hello World!".