Javascript: The First Script

JavaScript is a simple to comprehend and easy to use scripting language. When used in conjunction with a Web browser’s Document Object Model (DOM), it can produce powerful dynamic HTML browser-based applications. In this tutorial we will print the text in a web page as well as the time and date on your computer.

How to implement Javascript to an HTML page

So, how are we going to put our JavaScript into our pages? JavaScript implementation is quite similar to CSS. You can link to outside files (with the file extension .js), or write blocks of code right into your HTML documents with the <script> tag. So, the <script type=”text/javascript”> and </script> tells where the JavaScript starts and ends.

Browsers that do not support JavaScript will display the script as page content. To prevent them from doing this, we may use the HTML comment tag. If the browser understands JavaScript, it will pass the comment, even if it’s commented with the HTML tags. If it doesn’t understand JavaScript, it will not process it.

Have a look at the example below. It will do nothing! Actually, this is just the skeleton that you have to use every time you will write your script, except the comments that are optional.

<html>
<head>
<title>My First Script</title>
</head>
<body>
<script type="text/javascript">
<!--
//-->
</script>
</body>
</html>

Where to put Javascript

You can have JavaScripts in both the body and the head section. Scripts in the head section will be executed when they are called, or when an event is triggered. JavaScripts in the body section will be executed while the page loads; it generates the content of the page.

A Simple Script

Now let’s add some JavaScript code. At first we initialize a date object. Than we take control of the document object, and use its write() method to output some text to the document and other information contained in your browser.

 
<html>
<head>
<title>My First Script</title>
</head>
<body>
<h1>My First Script</h1>

<script type="text/javascript">
<!--
var today = new Date()

document.write("What a <b>wonderfull</b> day! Today is ");
document.write(today)
//-->
</script>

</body>
</html>

Save this code as firstScript.html and run it into your browser. Congratulations, you have now created your first web page with JavaScript.

Note:

What to do if visitors browsers don`t support Javascript or they just turned Javascript off. In this case you can use the <noscirpt> tag to give alternative content. Old browsers won’t understand the tag and so ignore it and display whatever is inside it. Modern browsers will understand it and skip its contents. Use it as follows:

<noscript>
<p>Sorry, but your browser does not support JavaScript.</p>
</noscript>

You should use this tag when appropriate — it helps keep your content accessible.

admin

admin

Leave a Reply

Your email address will not be published.