JavaScript Example
JavaScript code is easy to write and can be placed in three locations: within
the body tag, within the head tag, or in an external JavaScript file.
Let's start by creating our first JavaScript example.
<Script type="text/javascript">
document.write("JavaScript is a multi-paradigm");
</Script>
The script tag
indicates that we are using JavaScript.
The content type
`text/javascript` informs the browser
about the type of data being used.
The `document.write()` function is used
to display dynamic content with JavaScript. We'll explore the document object
in more detail later.
Three locations where you can place JavaScript code.
1. Within the body tag of HTML
2. Within the head tag of HTML
3. In a .js file (external JavaScript)
1. JavaScript Example: Code within the body tag
In the example above, we used JavaScript to display dynamic content. Now,
let's look at a simple JavaScript example that shows an alert dialog box.
<html>
<body>
<script>
document.write("Hello, World!");
</script>
</body>
</html>
2. JavaScript Example: Code within the head tag
Let's look at the same example of displaying a JavaScript alert dialog box,
this time contained within the head tag.
In this example, we're creating a function called `msg()`. To define a
function in JavaScript, you need to write the keyword `function` followed by
the function name, as shown below.
To call a function, you need to work with an event. In this case, we're using
the `onclick` event to trigger the `msg()` function.
<html>
<head>
<script>
function writeHello() {
document.write("Hello, World!");
}
</script>
</head>
<body>
<script>
writeHello();
</script>
</body>
</html>