Translate

Monday, 23 April 2012

Writing a Simple Program/code in JavaScript


In the previous chapters on JavaScript Basics, we studied how to insert JS code into html documents. We also mentioned that for the purpose of this course we will be using the Free code Editing software Called Komodo Edit.
So now lets start and write our first simple code.

Example 1

In the example below we will first display some text on the screen using Simple Html code. Then display the same text again using JavaScript command document.write.
first javascript code

RESULT (Page Viewed in Browser)

javascript code result

Example 2- Same Functionality but JavaScript Code in External File

STEP 1- In this example we will place the Javascript code in an external .JS file and link the html document to that.
STEP 2- The element to which we wish to apply some part of JS code(ex. function) from the External File, will be assigned a unique identifying name called 'ID'. In this case that is the paragraph tag. An ID is a unique identifier of an element.
JS External Script

STEP 3- Define a Function in the external .JS Extension Filejavascript external file


Above Code parts explained one by one.
window.onload- window onload is the event handler for page load
displaytext is the name of the function(you can assign name of your choice) that Javascript will execute when the page load event occurs. the function is defined below in the code.
Braces- under the brackets {} will come the code that will be executed when function is called.

document.getElementById("extmsg").innerhtml-
document. Look into the current document,
.getElementById. In the document go to the element with the given id name(in this case the <p> tag was given that id name)
InnerHTML , innerhtml changes the html code withing that selected element to the code written after the'=' sign.

RESULT (Page Viewed in Browser)

js result

Confusion- Html is also Displaying the Text, then why Use JavaScript?

Using programming we can automate the writing of the text and make it dynamic. That is browser can decide which text to write and under what circumstances to hide or display it. This type of decision making is not possible using simple HTML.
Its use will get clearer as we move on to writing more complex codes.


No comments: