Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

An overview about Javascript Functions and Events

In this article we will discuss about development with javascript. We will talk about functions and events.

Previously we had learned the basic concepts of Javascript as a language and learned how to write implicitly and explicitly.

Now we are going deeper in concept, JavaScript as a language got the concept of dividing code into pieces, i.e. functions must be exists.

JavaScript Functions:

Functions are written to organize my code look and kind of role separation. So someone can write .js code and another one can do the html elements. In addition performing code on event occurrence.

So the script that was written in a function will not be executed on page load, but upon called.

Function can take arguments or be argument-less and it can do some functionality without return to the caller “assume it return void” or return with certain value or event as following:

Listing 1: General Syntax

                         function func-name([arguments,...])
Simple function

Figure 1: Simple function

There's also predefined functions that can be used inside functions to perform certain task, the most commonly used are:

1) parseInt(String) , parseFloat(String)

Which convert string value to int, float , notice that the string value must at least start with numerical value otherwise it will generate NaN.

Ex: x=”10” -> y=parseInt(x) -> y=20


Which convert any number to its string, if radix is specified so it returns it to its radix string.

Ex: x=32 -> y=x.toString() -> y = 32

Ex: x=32 -> y=x.toString(16) -> y=20

Let's Go GUI

Very interesting feature in JavaScript is pop-up boxes which enable to alert, confirm or input.

1) Alert Box

Just view result or notification like this:

Alert box using Javascript

Figure 2: Alert box using Javascript

It's written as: alert(“Hello, I am Here”).

2)Confirm Box

It's to confirm that you wanna do some action, it appear with two options , ok or cancel.

Confirm box

Figure 3: Confirm box

It's written as: confirm(“Are you sure you want to exit”).

3)Prompt Box

Which is used as input :

Prompt box

Figure 4: Prompt box

Can be written as: var someString=prompt(“ text to be displayed in the prompt box”)

Now, we have more than basic knowledge in Java script, what about trying some code?

Demo 1:

The user will prompt to enter three different numbers, and through JavaScript the greatest, the least and the entered value will be displayed on screen.

The code will be as the following:

Listing 2: Simple JavaScript program to get max,min values.

	<title>Javascript tutorial - MrBool</title>
<script type="text/javascript"></script>

          var   num=parseInt(prompt("Enter the first number"));
          var   num2=parseInt(prompt("Enter the second number"));

          var   num3=parseInt(prompt("Enter the third number"));

             document.writeln("<br/>The first number is:"+num);

             document.writeln("<br/>The second number is:"+num2);

             document.writeln("<br/>The third number is:"+num3);

            var min=Math.min(num, num2);

            var min2=Math.min(min, num3);

             document.writeln("<br/>Min is:"+min2);

             max=Math.max(num, num2);

             max2=Math.max(max, num3);

             document.writeln("<br/>Max is:"+max2);


             document.writeln("Click refresh to reload");



Input for Listing 2

Figure 5: Input for Listing 2

Output for Listing 2

Figure 6: Output for Listing 2

Demo 2:

The second demo is to split text by a certain delimiter user enter.

Split text

Figure 7: Split text

Our JS Code should be as following:

Listing 3: Split text

	<title>Javascript tutorial - MrBool</title>
<h1>String Tokenizer</h1>

        <script type="text/javascript">

              var inp;
              var sep;
			  function getval()
		        var mya=inp.split(sep);
                            var any="";

				 for (var i = 0; i < mya.length; i++)


 document.writeln("<label for=\"substring\">Enter a sentence to split into words</label>");
			   document.writeln("<input type=\"text\" id=\"substring\" />");
			   document.writeln("<label>Split by</label>");
			   document.writeln("<input type=\"text\" id=\"sep\" />");
			   document.writeln("<input type=\"button\" value=\"Split\"  
		          document.writeln("<label for=\"substring\">the sentence split into 
		         document.writeln("<textarea id=\"txt\"rows=\"5\" 


JavaScript Events:

As JavaScript is interactive, so it must obey an Event request, i.e. it invoke itself on event calling like clicking a button, blurring an HTML Element.

In General it must handle events generated from outer sources “in our case HTML Elements”.

So, Event Handler Must be bind to an Element, so, consider that we have a button, and we want it to alert with a certain message upon begin clicked, that’s should go like that:

Listing 4: This listing will generate pop-up upon button click

<input type=”button” value=”click me” onclick=”alert('I am Clicked')”/>

Element can invoke a script by calling a certain function as following:

Listing 5:General event


   function showclickmsg()


        alert(“you press me!!!”)



<input type=button value=“click me”

common Event Handlers:

  • MouseEventHandlers : onMouseDown,onMouseUp,onMouseMove,onClick,onDblClick,onMouseOver,onDraStart
  • KeyboardEventHandlers : onKeyDown,onKeyPress,onKeyUp
  • OtherEventHandlers : onAbort,onBlur,onFocus,onError,onLoad,onBeforeLoad,onChange, onUnload,onMove,onSubmit, onStart.

Catching Errors in Javascript:

Errors can occur in scripting code like any other languages, so it must be handler to avoid annoying of website visitors.

It’s just few steps far from handling any error:

1) try .. catch

Listing 6: exception hadling

          try {
           // The code you want to run in the normal case.
           //The code to be executed if an error occurs
          //i.e. alert(err.description);

2)onerror event

Listing 7: exception handling in onerror event

          <script type="text/javascript">
                           onerror=handleErr //function calling
                         // Function to handle the  errors.
                                   function handleErr(msg,url,l){ 
                                                  //handle error here

Getting values in JavaScript:

Reading value of elements in a script is an easy matter, just call it by its id, name or even tag-name.

Calling elements by id get a specific element as id can't be repeated , calling elements by name will get all the elements that has that name, it's useful in reading checkboxes or radio buttons.

Calling elements by tag name will get all the elements with that tag name , i.e. if I get elements with tag name of all text, it will get all text fields in the document.

Now it's clear the difference between them all.

Let's see an simple example, we want to read value from text field on button click and prompt it to user using alert, the code should be as following.

Listing 8: Reading values

	<title>Javascript tutorial - MrBool</title>
               function getName(){
                      var name=document.getElementById('name').value;
                      alert('You Entered the name :'+name)
        Name<input type='text' id='name' />
        <input type='submit' value='Display name' onclick=”getName()”/>

Very simple, isn't it? Now we will talk about Javascript objects.

Javascript Objects:

Let’s see how JavaScript provide facilities to work with objects like: String, Date, Arrays, Boolean, Math and Dom.


While working with strings it's required to do some operations, like get string length, concatenate more than one, split string, get index of char in string, etc.

So, we have some predefined functions in JS that deal with Strings like:

Method Description Example Result
Length Return length of string

Var s="Hello World"

var len=s.length

chatAt(index) Return first occurance of character at certain index

Var s="Hello World"


toLowerCase() Return the string in small letters

Var s="HelloWorld"


toUpperCase() Return the string in caps

Var s="HelloWorld"


indexOf(str) Searching for the first occurance of string from position 0

Var s="Hello World"


split(str) Act as string tokenizer, as it split string according to str delimiter

Var s="Hello,World"


substring(l,x) Return substring from string begin from I to x

Var s="Hello World"



Working with dates and times is very easy, we need just to create date object which will hold the current date and time.

var date=new Date();

And it provides some methods to deal with date like:


Returns/set the day of the month (from 1-31).


Returns/set the day of the month (from 1-31).


Returns/set the day of the week (from 0-6).

GetFulYear()/set Returns/set the month (from 0-11).

Returns/set the year (YYYY).


Returns/set the year (YY).

GetMinutes/set Return/set the hour (from 0-23)

Returns/set the minutes (from 0-59)


Returns/set the milliseconds (from 0-999)


To store some data with single name arrays are used, and also it's easy to create array in JS.

Create an empty array -> var myArray = new Array();

Create an array with defined values for items: -> var myarray = new Array( "1", "2");

Create an array with a certain number of items:

var myarray = new Array( 3 );

Add element to an array:

myarray[0] = “val 1“

myarray[1] = “val 2“

To get Array Length: use length method as following, myarray.length.


Random Number using Javascript, each number refer to an image, it's just a game, you guess the next image will carry which number, and when you hit stop, it will show you number of correct guesses.

Guess Game

Figure 8: Guess Game

The code should be as following:

Listing 9 :Simple game

	<title>Guess Game</title>

<script type="text/javascript">
     var keynum;
     var keychar;
     var numcheck;
     var userscore=0;
     var currentImage = 0
     var imageArray = new Array(9)
                 for (i=0;i<9;i++)
                     	imageArray[i] = new Image()
	                     imageArray[i] = eval(i+1) + ".jpg"

                       function flip()
                           var rand_no = Math.random();
                           rand_no = rand_no * 9;
                           rand_no = Math.ceil(rand_no);

	                      if(currentImage == 9) 
	                   document.images[0].src= imageArray[currentImage]
	                   timerID = setTimeout("flip()",500)
//it's how to take input from user by hitting a key
              function alertmsg(e)
                     if(window.event) // IE
	                   {keynum = e.keyCode;}
                     else if(e.which) // Netscape/Firefox/Opera
	                    {keynum = e.which;}
                     keychar = String.fromCharCode(keynum); //it's where my key is


  function stopit()
	window.alert("Ur Scrore is "+userscore);


  function Set(cell,cursor)


<body onkeypress="alertmsg(event)">
<h1>Welcome to Guess Game</h1>	
<a href=""   onclick="return false;"><center><img class='imagem_artigo' src="1.jpg"   width=20% height=50%></center></a>	
<center> <input type="button" value="Start Game"  id="startgame" onclick="flip()" onmouseover="Set(this,'Hand')"></center>

 <center><input type="button" value="Stop Game" id="stopgame" onclick="stopit()" onmouseover="Set(this,'Hand')"></center>


Hope you enjoyed the article. See you next time.

My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login