Wednesday, March 6, 2013

  • Buffer

In previous Post Amazing Windows 7 Calculator UI Using Pure CSS3 I designed the UI of Window 7 Calculator. It won't do any calculations for us. In today's post We will make that calculator to do calculations for us. I am using Jquery to do this. Initially when i set down to write the code, I start with adding functions like add, subtraction,etc.. But myself felt it is beaming very complex. So i cut down all the scrap and I used JavaScript's built-in eval function. It make my work so simple. Lets jump in the code. See how i does it work.

Creating CalC object
//Calc Object with display,clear,doCal methods
var Calc={
 display:function(v){
  $("#display").val(v);
 },
 clear:function(){
  $("#display").val(" ");
 },
 doCal:function(val){
  var result="";
  var dtemp=$("#display").val();
  if(dtemp=="0"){
   this.clear();
   result=val; 
  }else if(val=="c"){
   this.clear();
  }else if(val=="="){
   result=eval(dtemp);
  }else{
   result=dtemp+val;
  }
  this.display(result);
 }
}
This is our main code. Javascript is object based language. In traditional OOP we first create Class and then create object using that class. But in JavaScript we first create object and then will add properties and functions to it. In this code we have 3 functions.
display will show result on Calculator screen.
clear will clear the calculator screen
doCal will do the actual calculation using eval method.

Detecting CalC UI button clicks
//calc UI click events
$('.calc button').click(function(e){
 e.preventDefault();
 Calc.doCal(this.value);
});
This code will be used to identify which key is clicked on Calc UI

Detecting Keyboard clicks
//Keyboard key press event.
$("body").keypress(function(e){
      Calc.doCal(String.fromCharCode(e.which));
});
This code is used to identify which key is pressed on keyboard. Here when a key clicked we will get ASCII code we can convert it into actual value using String.formCharCode method.

Complete Code
$(function(){
//Calc Object with display,clear,doCal methods
var Calc={
 display:function(v){
  $("#display").val(v);
 },
 clear:function(){
  $("#display").val(" ");
 },
 doCal:function(val){
  var result="";
  var dtemp=$("#display").val();
  if(dtemp=="0"){
   this.clear();
   result=val; 
  }else if(val=="c"){
   this.clear();
  }else if(val=="="){
   result=eval(dtemp);
  }else{
   result=dtemp+val;
  }
  this.display(result);
 }
}
//Keyboard key press event.
$("body").keypress(function(e){
 Calc.doCal(String.fromCharCode(e.which));
});
//calc UI click events
$('.calc button').click(function(e){
 e.preventDefault();
 Calc.doCal(this.value);
});
});

0 comments :

Post a Comment