Tuesday, 22 September 2015

Arithmetics1: Find Median number using Javascript.


Below is a simple javascript cooked up, that shows how to calculate the median number.
It calculates the median of the array [20,20,20,40,58,60,80];

function sortWell(a,b){
if(a>b) return 1
else if(a<b) return -1
else return 0
}
med=[20,20,20,40,58,60,80];
median=med.sort(sortWell)
num= median.length/2;
test_num= num.toString().indexOf('.');
m1= Math.ceil(num.toString());
m2=median[num]+median[num-1]
m3= m2/2
if(test_num!=-1){
document.write("Median number equals:"+median[m1-1]);
}else{
document.write("Median number equals: "+m3);
}
Result:

Median number equals: 40

Thanks for reading.

Arithmetics2: find mode(number with the highest occurence) using Javascript.


Here's another one. What it does is it helps you find the mode(number with the highest ocurrence) in an array.

function sortproperly(a,b){
if(a>b) return 1;
else if(a<b) return -1;
else return 0;
}
Array.prototype.mode=function(){
document.write("<table border=1>")
for(i=1; i<=9; i++){
sot= this.sort(sortproperly).join(',')
r= new RegExp(i+"\,[\d\d\,]?","g")
u= sot.match(r)
if(!u){
continue;}
document.write("<tr><td>Number:"+i+"</td><td>Frequency:"+u.length+"</td></tr><br>")
}

document.write("<tr><td><p style='color:red;'>The Mode is the number with the highest frequency.</p></td></tr></table>")
}

m=[2,3,6,2,3,2,2,2,2]
m.mode()
The result will be:

Thanks. God bless.

Creating dynamic tables in html- Converting json data to html table.


If you've been rolling with html for sometime now, i believe the table element i.e. <table> is not new to you.

There are many ways of creating dynamic table. In this article, we would be looking at how we can achieve this using json. I.e. Converting json to html table.

I assume readers reading this have some basic undestanding of html, javascript and json.
Lets start by creating a table that shows the first and last names of three of our employees.

Lastname Firstname
John Doe
Anna Smith
Peter Jones

To achieve this in html, we use the markup:

<table border="1">
<tr>
<th>Lastname</th>
<th>Firstname</th>
</tr>
<tr>
<td>John </td>
<td>Doe</td>
</tr>
<tr>
<td>Anna </td>
<td>Smith</td>
</tr>
<tr>
<td>Peter</td>
<td>Jones</td>
</tr>
</table>

We can accomplish the same task using the json to html table way. Its just some javascript that loops throught the json data and append its value to a table.


<script>
//Here we assign the json data to a variable named employees.
var employees = [ { "firstName" : "John" , "lastName" : "Doe" }, { "firstName" : "Anna" , "lastName" : "Smith" }, { "firstName" : "Peter" , "lastName" : "Jones" }, ];

//Table's header. document.write("<table border='2'><tr><th>Lastname</th>");
document.write("<th>Firstname</th></tr>");
//Loop and append
for(i=0; i<employees.length; i++){

document.write("<tr><td>"+employees[i].firstName+"</td><td>"+employees[i].lastName+"</td>");
document.write("</tr>");
}
document.write("</table>");
</script>

The above javascript will give the same table. I.e.

You can use this single javascript in multiple pages.
This comes in when you want to display the same table in multiple pages.
Just put the script in a .js file, and link it to the pages you want it displayed. Just like css.

e.g:
<script src="mytable.js"></script>

More data can also be added to the employees json object.

What makes this json to html way dynamic is the fact that json is a data format just like xml.
Data can be dynamic(change).
So converting dynamic json to a neater tabled format is not a bad idea.
Many apis are now adapting the json format also.
E.g the google direction api which is dynamic i.e. It changes.
It could go a bit more complex, but this article was written to give/show the basics of how the conversion of json data to html table can be done.

Download json2table.zip

Thanks for reading
God bless!

oluyaled@gmail.com
http://davolu.blogspot.com

(AJAX)Javascript HTTP request


(AJAX)Javascript HTTP request part1

Javascript also supports the HTTP request. With the HTTP request, we can write scripts that can GET or POST data. It is a way of communicating with web servers i.e.
Client-> server
or
server->client
In this part1, we will discover how to initiate the HTTP class or object and then open a file.
Initiating the HTTP class or object
The first step is to create an instance of the class or object.

//Initiating the class for browsers that dont support the microsoft ActiveXObject i.e safari, opera, chrome...

if(!window.ActiveXObject)
{
http= new XMLHttpRequest();
}
//For those that support ActiveXObject i.e microsoft Internet Explorer.
else{
http= new ActiveXObject("Microsoft.XMLHTTP");
}

After initializing the class or objects as done above, we can now open/access any file on the same domain using the open() method and view the content using the responseText

Note that trying to open google.com would generate an error since google is not on your web domain.

So lets put it all up together.
We open a file named test.txt
The file contains the text: "hello you!".
And then we finally alert its content.

//a variable "http"
var http= null;
//Initiating the class for browsers that dont support the microsoft ActiveXObject i.e safari, opera, chrome...
if(!window.ActiveXObject)
{
http= new XMLHttpRequest();
}
//For those that support ActiveXObject i.e microsoft Internet Explorer.
else{
http= new ActiveXObject("Microsoft.XMLHTTP");
}
//open a file named test.txt
//Note that the file must be in our domain.
http.open('GET','test.txt',false);
http.send(null);
//alert the content.
alert(http.responseText);

Its as easy as that. The result will be :

hello you!

The content from the test.txt file is extracted and printed on our page. It can be any file i.e .html, .css...
This is a basic use and introduction to using HTTP request in javascript. More methods and techniques will be dealt with in later parts of this series.

To rap it all up, lets create a function named openDOC. Our little function will allow us to open files in our domain when called as thus: openDOC("test.txt");

function openDOC(url){
//a variable "http"
var http= null;
//Initiating the class for browsers that dont support the microsoft ActiveXObject i.e safari, opera, chrome...
if(!window.ActiveXObject)
{
http= new XMLHttpRequest();
}
//For those that support ActiveXObject i.e microsoft Internet Explorer.
else{
http= new ActiveXObject("Microsoft.XMLHTTP");
}
//open a file passed as an arguement in the openDOC function.
http.open('GET',url,false);
http.send(null);
//alert the content.
alert(http.responseText); }

Then to run it:

openDOC("test.txt");

Truncate strings in Javascript

Truncate strings with javascript

Javascript doesn't have an inbuilt function for truncating string(I haven't seen one).
When i say truncate i mean something like shorten. E.g the sentence "David was a mighty King" could be truncated to "David was a..."
I hope you get the gist now

So we would make a function we name trunc. It will actually be a String prototype. The trunc function will be used as follows:

//The string

var str="Examples of fruits are: apple, mango, orange, coconut, banana,cashew and cherry. God made them all."

//trunc to the rescue!

document.write(str.trunc(44))

The result will be:

It returns only the first 44 words and append '...' to it.
Okay! So here's the simple function. This is accomplished using substring. Use can also use substr.

The function:

String.prototype.trunc=function(x){
return ""+this.substr(0,x)+"...";
}
And the use:
var str="Examples of fruits are: apple, mango, orange, coconut, banana,cashew and cherry.
God made them all."
alert(str.trunc(44))
//alerts: Examples of fruits are: apple, mango, orange...

Thanks and God bless.



Wednesday, 15 July 2015

How to get the maximum number from a series digits in Javascript


This is a simple function that returns the highest number in a series of numbers.

  function max_series(x)
  {
      h=0;
      for(i=0; i= h)
          {
              h=arguments[i];
          }
          
      }
      return h;
  }



A simple way to use the function would be:

  
var maximum = max_series(2,3,4,5,5.5);
alert(maximum); //alerts 5.5



Tuesday, 7 July 2015

A formula for drawing circular buttons with css




The button you see above is not an image. Its a simple html button that has been given a circular shape using CSS.
I want to share a simple formula I use personally for making these buttons and other html elements circular in shape.
The following code below creates the circular button:

<html>
<head>
<title>A circular button</title>

<style>

.circle_shape
{
border: solid 1px green;
width:150px;
height: 150px;
border-radius: 180px;
}

</style>

</head>

<body>

 <input type="button" class="circle_shape" value="I am a circular button"/>


</body>
</html>

An input element of type "button" is put in place. The class is set as "circle_shape" and it's value is given as "I am a circular button".


 <input type="button" class="circle_shape" value="I am a circular button"/>
Then we set the style.

.circle_shape
{

width:150px;
height: 150px;
border-radius: 180px;
}


The maths I use is easy.
i. Let the value of the width and height be the same.
ii. The border-radius value should be the value given to the width and height + 30.
Following the maths above, valid style for the circular shape are:

.circle_shape
{

width:250px;
height: 250px;
border-radius: 280px;
}



.circle_shape
{

width:30px;
height: 30px;
border-radius: 60px;
}


and so on...