HTML, CSS, Javascript, and jQuery: Putting them all together (Part 2)

On my previous post, I talked about HTML and CSS.  Now I’m going to talk about Javascript

Javascript is a popular scripting language that makes an HTML page dynamic.  To add Javascript code, you use the <script> tag and you can put them in the <head> or in the <body> section of the HTML page.  It is recommended to put all of them in the <head> section.  Below is an example of a Javascript function being called on a click event of the <p> tag.

<head>
<script type="text/javascript">
function myFunction()
{
alert("Hello, Universe!!!");
}
</script>
</head>
<body>
<p style="font-weight: bold; color: #0000FF" onclick="myFunction()">
Hello, World!!!
</p>
</body>

 

Remember that Javascript code are executed as the HTML page is being parsed.  The example below will display the message when the HTML page is being loaded without having to wait for any event.  Notice that the Javascript code is not contained in a function declaration like the example above.

<head>
<script type="text/javascript">
alert("Javascript code not belonging to any function");
</script>
</head>

 

If you have lots of Javascript code, it is preferred to put them in an external file with extension .js and use the <script> tag’s src attribute to point to this file.  That way you can also use this file in the other HTML pages.

<head>
<script src="MyJavaScript.js"></script>
</head>
<body>
<p style="font-weight: bold; color: #0000FF"
onclick="myAnotherFunction()">
Hello, World!!!
</p>
</body>

 

The file MyJavascript.js contains the following Javascript code:

function myAnotherFunction()
{
alert("Hello, Big Bang!!!");
}

 

Next post, I’ll cover the jQuery.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s