Friday 4 March 2011

JavaScript - The Next Step

Introduction

When dealing with business organisations, an eye catching web site it’s a must. Mainly, organisations use their web site to promote their products and to reach customers. A web site has no geographical limits and provides a competitive advantage. The infrastructure (Internet) enables organisations to reach customers all over the world.
To enhance a web page and make it more attractive, web developers can use JavaScript to create animations and interactive objects. Such web pages are known as DHTML or Dynamic HTML pages.

Why Dynamic? 
Pages are Dynamic because the contents can change according to user actions. For example, contents can change when a user clicks a button or move the mouse over an object.  
This blog describes my experience while creating and implementing a JavaScript animation project assigned by my tutor.

My First Interactive Project

Web pages can be designed to update the contents when a user performs an action. This can be achieved using Event Handlers.  To describe Event Handlers, I created an interactive web page that performs some actions and uses the onmousemove and onclick event handlers.
The aim is divided in two:
  • Create a picture that moves when the user hovers the mouse.
  • While hovering, if the user clicks the mouse, a copy of the picture is inserted where the user clicked. 
The HTML markup page consists of the following code:
 
The <div> tag in line 40 contains all Event Handlers. The JavaScript function onMove() is called when the user hovers the mouse over the <div> tag. The JavaScript function onClick() is called when the user clicks in the <div> tag area.
The <div> tag between lines 42 and 45 displays the current mouse position using <span> tags. The mouse positions (X and Y) are updated automatically when the mouse moves.
The <img> tag at line 47 moves with the mouse pointer (cursor).  Note that the position style is set to absolute, this instructs the HTML that the image is not fixed; this enables the JavaScript function to move the image.
The JavaScript function onMove() is executed when the user hovers the mouse over the <div> tag described above.
When an event occurs a JavaScript event object is created. This contains additional information related to the event that has occurred. For more information refer to http://www.elated.com/articles/events-and-event-handlers/.
Amongst others the event object has the mouse X and Y positions. Where;
  • X – is the cursor relative distance in pixels from the left.
  • Y – is the cursor relative distance in pixels from the top.
In lines 9 and 10, the X and Y  cursor coordinates are stored in variables ex and ey respectively.
In lines 12 and 13, using the getElementById(), the image top and left positions are changed to variables ey and ex.
In lines 15 and 16, the <span> tags are updated with the new values using the innerHTML.
The JavaScript function onClick() is called when the user clicks on the <div> tag (described previously). Similar to the onMove() function, the X and Y cursor coordinates are stored in variables ex and ey. These coordinates reflects the new image position.
In line 24 the <div> tag is stored in a variable called mainDiv. Using the createElement() method a new image is created and stored in a variable called imageNode. The new image properties are defined in lines 27 to 31. Using the appendChild(), the new image is added to the <div> tag in line 33. The final output is shown in the screenshot and video below:

Animation

The setTimeout() method

The setTimeout() method is used in JavaScript to call functions after a specific time interval. The following button when clicked, waits 5 seconds and then calls the displayHello() function.
The time specified in the setTimeout() is in milliseconds and the function is only executed once. 

The setInterval() method

The setInterval() method is used in JavaScript to call a function continuously after a specific time interval. The function will keep executing similar to an infinite loop until clearInterval() is called. The following example shows a simple timer program.
Within the HTML <body> tag the following objects are added:
  • In line 18, a <span>tag is used to display the time
  • In line 19, an <input> object is used to call the increment() function every second. This function is declared in lines 10 to 13.
  • In line 20, an <input> object is used to call the clearInterval() method and stop the timer.
Note,to use clearInterval(), the setInterval() method must be assigned to a variable (timerObject).

Task Description

This blog describes my experience while performing a task assigned by my tutor. The task consists of the following stages:
  • Using HTML, CSS and JavaScript and some images, create a web page and an animation of a man running.
  • Add functionality to enable the user to speed up and slow down the animation.
  • Add a function that enables the user to ‘throw’ an obstacle and stop the runner.
  • Add a custom feature.

My Design

The project

The project files are divided in three:
  • The HTML code – this file contains all HTML markup tags
  • The Style sheet – this file contains all CSS styles
  • The Scripting file – this file contains all JavaScript functions and variables
The HTML file is linked with both the style sheet and the scripting file as shown in the following code:

The HTML code

The HTML markup for my task is made up of the following <div> tags:

The SeparatorDivTop and SeparatorDivBottom

These two <div> tags are used to display two different images around the animation (top and bottom). All attributes are declared within an external style sheet. The two CSS blocks that define the properties are shown below:

The MainDiv

This <div> tag is used to contain all the animation and is made up of the following four <img> tags:
  • fence – the background image
  • man – the running man
  • car  an image for my custom animation
  • ball – the image that is used as the obstacle.
The HTML markup is as follows:
Note, since car and ball are only visible when the user performs an action, by default these images should be hidden. To hide an image in CSS, you must assign the none value to the display property.

The ControlDiv

This <div> tag is used to contain all user controls. Within this <div> tag a user can perform the following actions:
  • Start or Stop the running man
  • Increase or reduce speed
  • Launch the car animation
  • Throw the ball and stop the running man.
To handle user events, the <input> object is used. A button was created for each function mentioned above. To display buttons evenly, all buttons are added within a <table> tag.  The controls are shown and described below:
The Start and Stop buttons call the Start() and Stop() JavaScript functions respectively. As the name implies these buttons are used to start and stop the running man.
The Faster and Slower buttons call the Fast() and Slow() JavaScript functions respectively. These functions will reduce and increase the animation interval time; making the running man go faster or slower. The interval time is displayed in a <span> tag.
The Insert car button calls the CarCase() JavaScript function. This function includes a jumping car, and gives the impression that the running man is being chased. When the car is added the running man automatically speeds up. To stop the car chase, users must click the Insert car button.
The Bounce ball button calls the BounceBall() JavaScript function. This function throws an obstacle (bouncing ball) that stops the running man. To remove the bouncing ball, users must click the Bounce ball button.

CSS annotations

Amongst all properties in my CSS file, I would like to focus and describe two in particular:
  • The Position
and
  • The Z-Index

The Position

To be able to position images in their correct location and make them overlap each other, I used the Position CSS property. By default in HTML, all objects float; will not overlap each other. The following shows an example of floating images:
To ignore floating and position an images at a specific location, the absolute value should be used. The following code shows an example that includes the absolute value:
When using the absolute value, the top and left CSS properties can be used to specify the object exact location.

The Z-Index

The Z-Index property enables you to specify the display order when objects overlap each other. For example, in the running man task, two images overlap each other; the fence and the running man.
To specify how objects should be placed in my animation, I included the Z-Index property in the CSS style as shown below:
The greater is the Z-Index value, the more visible is the object. So in this case the running man will be in front of the fence.

The JavaScript code

The Running Man

The animation is made up of six different images. Using the JavaScript setInterval() method, the images will continue to iterate until a clearInterval() is called.
When creating animations that include images, it is recommended to load the images in memory at start up. This process is called Caching. If the images are not cached, the browser will attempt to download the image on the client side when needed; making the animation slower.
The following code shows the images used for the running man being cached:
At line 7, an array is declared to store all image objects. In lines12 and 13 a for loop is used to assign a new Image object to each array item. In lines 16 to 21, each image source path is configured using the src property.
At line 5 a variable that stores the current image being displayed is declared and assigned the 0 value (Arrays start at 0). The variable declared at line 6 is used to store the setInterval() object.
The following code checks the current image displayed and moves to the next image:
This function will first check the currRunner value; this indicates the current image displayed. If the current image is 5 the function will set the currRunner to 0 to re-start from the first image. If the current image is not 5 the currRunner is incremented by one, thus moving to the next image. In lines 72 to 75, the same algorithm is used to display the moving fence. At lines 77 and 78, the man and fence <img> tags are updated with the new images.
The Start() function is called when the user clicks the Start button.
At line 83, the clearInterval() is used to prevent a user from starting an interval that is already running.
At line 84 the setInterval() is created and stored in variable startRunning. The interval, calls the MoveNextStep() function at an interval speed stored in a global variable (speed). Storing the speed in a global variable is required, because this enables you to increase and reduce the interval speed from any function.
To enable the user to view the current speed, at line 85 the UpdateSpeed() is called. This updates the innerHTML() in the <span> tag.
Lines 89 and 90, ensures that the bouncing ball is hidden when the user clicks the Start button.
The Stop() function is called when the user clicks the Stop button.
At line 95, the clearInterval() is used to stop the interval stored in startRunning. When the animation stops, the man image is updated (line 96) and the speed is set to 0 (line 97).
Lines 101 to 102 ensures that the car is hidden when the user clicks the Stop button.
The Fast() and Slow() functions are called when the user clicks the Faster and Slower buttons.
First the function checks if the running man animation is started. This is done by checking the value of a flag (isRunning). If the animation is started the speed is decremented or incremented by 10 milliseconds.
These functions also include the algorithm to keep the values between 10 and 200 milliseconds.

The Chasing car

The car chasing animation is very similar to the running man animation. Image objects are saved in an array car[] and the current image is stored in a variable called curcar. The CarCase() function is called when the user clicks the Insert car button. Using the setInterval() method, the MakeCarJump() function is called every 100 milliseconds.
Since the same button is used to start and stop the car chase animation, the function first checks if the animation is started. If the animation is already running, the animation stops and vice versa.
One thing to note in this code is the syntax used to make the car visible. By default the car <img> tag is hidden using style="display:none" in the HTML markup. To make the car visible the syntax in line 139 below is used. On the other hand to hide the car the syntax in line 133 is used.

The bouncing ball

The bouncing ball animation is very similar to the car chasing animation. Image objects are saved in an array ball[] and the current image is stored in a variable called curball. The BounceBall() function is called when the user clicks the Bounce ball button. Using the setInterval() method, the MakeBallBounce() function is called every 130 milliseconds.

The final output

The output of my design is shown in the following video:

Cross Browsers

The running man animation was tested with successful results on the following browsers:
  • Internet Explorer
  • Firefox
  • Google Chrome
  • Safari

Paint.net – Good to have

Paint.net is a photo and image editing application that helped me a lot while modifying the images used in this project. Amongst others I used Paint.net to:
  • Change image colors
  • Resize images
  • Set image transparency
Paint.net is available from http://www.getpaint.net/. 

Conclusion

As time goes by, JavaScript is becoming one of my favourite programming languages. I ‘am very satisfied with the result obtained from this task and in the future I would like to go deeper in the subject.
I recommend trying some online tutorials available at W3Cschools or from Developing Web Application (my course work handbook by Ralph Moseley). Lot of images exist online that can be downloaded and used for free in your animations. Once you learn the basics, it will not take long to create your own JavaScript animation.
Enjoy coding!!!

No comments:

Post a Comment