Friday, 30 March 2012

Javascript Calculator

In this post, I am going to show you how to make a simple calculator that runs in a web browser using HTML & Javascript. Below is a screenshot of what you might achieve after going through the steps I will provide.


Calculator app with java script


Image of calculator

AIM
To make simple calculator that can add, multiply,subtract, divide, find the power, and find the mod of numbers. This calculator has a history feature which will enable you go back to previous computations. The history can be hidden/shown and cleared as well. The calculator should be able to receive keyboard inputs also instead of clicking buttons.


What you should have!
- A text editor preferably Notepad++.
- A web browser(like chrome or firefox)
------------------------------
Ok Lets Start!!
If you have some experience with HTML, you can do some fancy calculator Graphical User Interface(GUI). However, if you just a beginner and want to tryout stuff, you can use the normal HTML tables to create the GUI of the calculator. I suggest however that having some fundamental knowledge in HTML would help you understand the GUI code better.

I will display the HTML code below. Before you copy and paste, be mindful that I used images as buttons and stored the images in a folder called gfx. Also, this calculator also responds to mouse hovers and there are images for those also. So what you can do is you can find where there are "src=url" and remove all those from the HTML and change all the input types to buttons for each input type,
 OR you can create custom images but make sure you use the naming conversion used in this HTML. for example, the key "1" is 1.bmp. and yah your image files should be bmp.They can be png or jpg if you want however you have to modify the HTML to take that into consideration. If you don't get this part, you can drop a comment and I will be glad to answer you.



<html>
   <head>
   </head>
            <body>
                <!--<div id="morethings" style="visibility:visible" align="center" >
                            <textArea readonly="readonly" id="histoy" rows=5></textArea>
                        </div>-->
                <table id="calculatorLayout" style="border:1px solid;box-shadow:0px 0px 10px 1px rgba(100,100,100,1)" align=center>
                   
                    <tr id = "historyRow"><td colspan=2>
                   
                       
                        <div id="morethings" style="visibility:visible" >
                            <textArea readonly="readonly" id="histoy" rows=9 cols=6 style="max-height:200px;min-height:200px;max-width:200px;min-width:200px"></textArea>
                        </div>
                           
                        </td></tr>
                    <tr bgColor=lightGreen>
                   
                    <td height = 30 colspan = 2 >
                            <span id="values" ></span>
                        </td>
                    </tr>
                    <tr>
                        <td colspan=2><a href="#" onclick="hideHistory()">show/hide history</a><|||><a href="" onclick="clear()">clearAll</a></td>
                    </tr>
                    <tr>
                    <div id = "buttons">
                        <tr><td>
                            <input type=image value="^" src="gfxCalc/exp.bmp" onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)" onKeyPress="detectKey()">
                            <input type=image value="mod" src="gfxCalc/mod.bmp" onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)" onKeyPress="detectKey()">
                        </td></tr>
                        <td>
                        <input type=image value="7" src="gfxCalc/7.bmp" onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)" onKeyPress="detectKey()">
                        <input type=image src="gfxCalc/8.bmp" value = 8 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)">
                        <input type=image src="gfxCalc/9.bmp" value = 9 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td><td><input type=image src="gfxCalc/plus.bmp" value = "+" onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td></tr>
                        <tr><td><input type=image src="gfxCalc/4.bmp" value = 4 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)">
                        <input type=image src="gfxCalc/5.bmp" value = 5 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)">
                        <input type =image src="gfxCalc/6.bmp" value = 6 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td><td><input type=image src="gfxCalc/x.bmp" value = "*" onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td></tr>
                        <tr><td><input type=image src="gfxCalc/1.bmp" value = 1 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)">
                        <input type=image src="gfxCalc/2.bmp" value = 2 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)">
                        <input type=image src="gfxCalc/3.bmp" value = 3 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td><td><input type=image src="gfxCalc/minus.bmp" value = "-" onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td></tr>
                        <tr><td ><input type=image src="gfxCalc/dot.bmp" value = "." onclick="detectBtn(this)">
                        <input type=image src="gfxCalc/0.bmp" value = 0 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)">
                        <input type = image src="gfxCalc/dive.bmp" value = "/" onmouseover = "buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td><td>
                        <input type=image src="gfxCalc/equals.bmp" value = "=" width = 50 onmouseover="buttonFxOver(this)" onmouseout="buttonFxOut(this)" onclick="detectBtn(this)"></td></tr>
                       
                    </div>
                   
                   
                </table>
            </body>
    </html>




Ok lets continue...
Now if you paste this code and try to open it with a browser,  you will see a page that has a rectangular shape with some objects on it.

Now to the logic part. I suggest here to that some fundamental Javascript would help.
To start writing javascript, you need to put the script inside of a script tag like so

<script type="text/javascript">
</script>

Now the first function we are going to write is the detectBtn() function. This function has a parameter which is the object/ the button that was clicked. In order start any computation, you need to know what button was clicked.

function detectBtn(clickedBtn){
    myButton = clickedBtn;
   checkBtn(myButton.value);

}

From this function, we can see that the function detectBtn calls another function checkBtn and supplies the value of the button that was clicked. The value of the button is the value that is specified in the value attribute of the HTML.

The function checkBtn goes on to do more complex things like determining whether an equal sign was clicked and or a sign was clicked among other things. I will write code for the function and I will explain

function checkBtn(buttonVal){
//the comments in this function should help you understand what they are doing
                    for(var i =0;i<signs.length;i++){//loop checks whether the current object is a sign or not
                        if (buttonVal == signs[i]){//if it is a sign, it calls the signclicked function and isSign is true
                            signclicked(buttonVal);
                            isSign = true;
                            break;
                        }
                    }
                    

//I wanted to use this if statement to check if the user had already pressed
//a dot. You know we can't have two dots in a number.

                    //if(currentObj.value="."){
                        //isDot=true;
                    //}
                   
                    if (buttonVal=="="){
                        isSign=true;
                        histoy.value=histoy.value+calcArr[2]+"\n";
                        calculate();
                        drawLine();
                        //values.innerHTML = calcArr[0]+"";
                        signState=false;
                        firstNum="";
                        //opDone = true;
                        //calcArr[0]="";
                    }
                   
                    if (!isSign){//this decides whether to store the operands for the operation or store the operator
                        storeOperands(buttonVal);
                    }
                    isSign=false;
                } 


//to be continued... Stay tuned

Monday, 13 February 2012

Dynamic HTML with Javascript


Dynamic HTML with Javascript.

Aim
Our aim was to create a dynamic HTML webpage with Javascript.

Description:
We were given an HTML page that had a table created and designed with CSS style sheet. There were menus and editors created in DIV tags but were made invisible and had an absolute position which means that their position is not affected by the position of the parent element/tag. Some ONCLICK events were given to some of the HTML elements that would the functions in the script to perform some changes to the current or original HTML page.

Objectives
Our objective was to let the table respond to the onclick event by showing a popup menu or make a popup menu visible. Again the popup menu should appear at the position of the mouse click. Also the row that was clicked should be highlighted. It should be possible to add, edit and rows of the table that has been created. Again, when you click on edit in the popup menu, the contents of the row that was clicked must appear in the edit row text fields.

Implementation
The first function that is called when the page registers a click is the showPopupMenu(obj). This function shows the popup menu that gives the user the option of either edit, add, delete and a cancel option.

deleteRow()
The delete function just calls an inbuilt function called deleteRow with the index as arguement. This removes the specified row from the HTML.

addRow()
The addRow() function adds a row at the end of the last row. This is done getting the total number number of rows in the table so that the new row could be added after the last row. After the row is added, cells for row are created. Moreover, since the rows should have an onclick event, you set the attribute for the new Row that is created. Again, I added a code that would alternate the background colors of the rows switching between blue and white. Since by default all the even numbers were blue, I calculated for the modulus of the row index by 2 and when the remainder is zero, the background becomes zero. The problem with this is that, when a row is deleted, the colours of the rows mess up. Lastly what I did was to make the browser that the addRow() function has been called by changing the byAdd Boolean variable to true. The addRow() then calls the showPopupEditor().

showPopupEditor()
This function basically makes the <div> that has the editor for the rows visible. The editor will have as default content the information on the current row that is clicked. In a situation where there is not current row clicked ie the add function was called first by the testAddRow link, then there are no values in the text fields. In this function, it checks which function called it and therefore determine whether to add the Row at the end of the table or to modify the content of an existing row when save link is clicked. After the save click link is clicked, the <div> becomes invisible.

SavePopupEditor()
This function actually does the adding or editing of the cells of the table. This function works with information of whether the it was called by the addRow function or the user just wanted to edit the rows and cell.


Data validation with Javascript


Validating a web form with Javascript

Aim:
The aim of this practical is to ensure that the data that is entered is valid with respect to the formatting and the types of characters that are present within it. For example, A name should not have numbers, an email is supposed to have the @ sign and the @ sign is supposed to before the last dot.

Objective:
Our objectives are to create an HTML form with input boxes that receive user inputs and calling the respective functions that checks the validity of the values of the inputs boxes before submitting it the data to the server. All errors were to be displayed in the innerHTML attribute of the span element of the HTML page.

Implementation:
With this page, I used a table to hold all my objects on screen. I gave all the objects I would be referring to in the script “ids” so that I could get access them. To get an object in the HTML page with script to use, the getElementById(“objectID”) method of the document class is used. From one of the examples we did in class, I realized I could use the form id in the script directly without having to get the form object (document.getElementById(“formId”)) in the script like using the form Id to call methods of the form object and even get access to the other elements of the form. For example take a form with id = myForm. In the script, one can just say myForm.elements(“myTextBoxId”). When I used this format to get my input boxes object in the form, it seemed to work however after sometime, I realised the browser did not respond to the event triggers and no error registered in the debugger’s console. After speaking to some of my friends who explicitly got the form object before using it, I realised later the code format I used (ie using the form id directly) might not be supported by all browsers.
With the validation of data, we used mechanisms like comparing the string the user entered with a regular-expression object. This mechanism also came with its own problems. First of all, one had to know the format of the regular expression parameter to correctly specify the behaviour/characteristic of the regular expression object. For example [A-z] or [A-Z,a-z] is for characters from capital A through to small z. The regex can get complex once you want a quite a complex characteristic. For the regex I used ([A-z]), I intend it to be used only alphabets, however after doing the comparison, it was able reject only numbers but accepted the combination of numbers and alphabets.
  

Static HTML page


Creating Webpages with HTML   Blog1

Aim:
In this assignment, we were supposed to create static web pages with HTML. The HTML page should consist of images, hyperlinks, lists, table, headings and formatted text.

Objective:
Our objective for this assignment was to create two Web pages that were linked together with the use of hyperlinks. The first page should basically have the information about the company whereas the second page informs the visitor of site about the company’s executives and directors.

Implementation
After looking at a couple of web pages I had created in my freshmen year during the programming one course, I was ready to start with the assignment. With the basic knowledge I had in the creation of Web pages, I thought using a table to represent all the information that will be displayed on the screen. I also designed some images that were later added to the page to make it more visual appealing. 
The arrangement of the HTML objects in the table was a bit of a problem because I did not really understand the manipulations of the rows and columns of a table using the colspan. Usually if I wanted some text or image to occupy a whole row, I assign a large number like 7 to the colspan attribute of a row. I later got to understand that the colspan attribute expands a columns across a row thereby making other colums smaller or deleted. With the knowledge of this, I used this to form the layout of table and hence determining where images, text and hyperlinks are located.
Again, another issue concerning the creation of the web page was the size of the images used. It was a bit hard determining what size of photo to be used. I had to do a little trial and error to fit the images appropriately. I also realized that every image I tried setting was tiled at the position I put it so that also added to my experimentation on the size property of the cell I was insert the image.

Google Sites:
For this, our aim was to web development technologies from google to create web pages without writing HTML code. This seemed easier since everything you wanted to see was just a click away. I was given an array of templates to choose from for everything I wanted to do.
The only problem with this was that it was hard to figure out how to reverse changes made to your web page. Apart this, everything else was quite straight forward.