Sponsors

 

Tuesday, April 1, 2008

JS Animation - Pulsate DIV Elements Tutorial [Pt. 2]

As promised here is the second part of the JS Animation series. If you missed out on the first one, it was JS Animation - Fade/Appear DIV Elements Tutorial [Pt. 1]. In this tutorial we'll Pulsate DIV element using JS and no other libraries.

If you have any problem during the tutorial I suggest you drop by our forum, I also suggest you download the necessary files so that you can understand everything better while it is happening.

I hope you remember the setOpacity() function that we wrote last time. It remains the same. For those who've forgotten, here it is again -

function setOpacity(domId, val) {
obj = document.getElementById(domId);
obj.style.MozOpacity = val;
obj.style.opacity = val/10;
obj.style.filter = 'alpha(opacity=' + val*10 + ')';
};


Now for some pulsating. When a DIV elements pulsates, we basically make it fade and then appear very fast but never actually hide. It is an effect that is used to bring attention to that element.

What we'll be doing for our pulsation function is -
  1. Ask for the domID of the div and the number of times it needs to pulsate.
  2. Get the DOM Element and check if it is visible or not.
  3. If the number of pulses isn't given, then set it to a default 4.
  4. Set the variable alpa to 10, and ch to -1.
  5. ch, will be the variable that'll determine the rate of change of the opacity of the DIV.
  6. We'll multiply times by 2
  7. Now we'll make an internal function p(), this'll do the actual animation
  8. Rest of it is explained in the code with comments

function pulsate(domId, times){
obj
= document.getElementById(domId); //Get the Element
if(obj.style.display == "none") return false; //Return false if the element is hidden
if(!times) times = 4; //If the user doesnt specify the no. of times he/she want pulsation
//Add a default value of 4.
var alpha = 10; //Set the initial value of alpha to 10 (Opaque)
var ch = -1; //The rate of change of the opacity
//Currently negative, as first it'll fade
times *= 2; //Multiply the 'times' given my user by 2
function p(){ //Internal function
alpha += ch;
/*Change the alpha according to the ch
variable that could be positive or negative*/

setOpacity
(domId, alpha); //Set the opacity of our element to the specified alpha
if((alpha < 0 || alpha > 10) && times > 0){
/*If the alpha has gone out of range and times
and it hasnt pulsated enought number of times...*/

times
--; //Decrement times
if(ch<0){ //If ch is +ve make it -ve
ch = 1;
}else{//If ch is -ve make it +ve
ch = -1;

}
}
if(times > 0 ) setTimeout(p, 10);

};
setTimeout
(p, 10); //This is where we call the f() function for the first time
};

I hope you get it. If you have any problem, drop by on the Google Group, and download the necessary files.

JS Animation - Fade/Appear DIV Elements Tutorial [Pt. 1]

I was thinking of doing a series of tutorials on the different effects that you can code and apply on DIV elements, without the use of any library. Today we'll start of with a very basic effect of toggling the visibility of the DIV - fade and Appear.

If you have any problem during the tutorial I suggest you drop by our forum, I also suggest you download the necessary files so that you can understand everything better while it is happening.

To do any of the above animations, we'll have to change the opacity of the DIV element. We write the following function to change the opacity successfully in all browsers -


function setOpacity(domId, val) {
obj = document.getElementById(domId);
obj.style.MozOpacity = val;
obj.style.opacity = val/10;
obj.style.filter = 'alpha(opacity=' + val*10 + ')';

};

So we first ask for the domId of the element, then get that element by Id and change its style to get the desired opacity. Remember the val can range only between 0-10. Now for the actual animation.

Fade
To fade the object we first check whether or not that element is already hidden (if it is we return false). We make a variable alpha with value of 10, and a also a function f(), inside the function fade(domID). We call this function f(), from inside itself after every 100 milliseconds till alpha becomes 0, and once the alpha is 0, and we can't see it, we hide the element.

function fade(domId){
obj
= document.getElementById(domId); //Get the Element

if(obj.style.display == "none") return false; //Return false if the element is already hidden

var alpha = 10; //Set the initial value of alpha to 10 (Opaque)
function f(){ //Internal function

alpha--; //Decrement the alpha value
setOpacity(domId, alpha); //Set the opacity of our element to the specified alpha

if(alpha > -1){ //If alpha is still bigger than -1 then..
setTimeout(f, 100); //..then call the function again after 100 milliseconds

}else{ //otherwise..
obj.style.display = 'none'; //..otherwise now that we cant see the element anyways, hide it

}
}
setTimeout
(f, 100); //This is where we call the f() function for the first time

};


Thats pretty much it. Now to fade any div all you need to do it fade('divId'); and you'll get beautiful animation on your page.


Appear
To fade the object we first check whether or not that element is already being displayed (if it is we return false). Then we un-hide the element and then start the animation. We make a variable alpha with value of 0, and a also a function a(), inside the function appear(domID). We call this function a(), from inside itself after every 100 milliseconds till alpha becomes 10.

function appear(domId){
obj
= document.getElementById(domId); //Get the element

if(obj.style.display != "none") return false; //Return if it is already being displayed

obj.style.display = ''; //Un-hide the object before its animation
var alpha = 0; //Set the initial value of alpha to 0 (invisible)

function a(){ //Internal function
alpha++; //Increment alpha

setOpacity(domId, alpha); //Set the opacity of our element to the specified alpha
if(alpha < 11)setTimeout(a, 100);

/*Till alpha is 10, keep calling the
a() function after 100 milliseconds */

}
setTimeout
(a, 100); //This is where we call the a() function for the first time

};

Done! Now you have your fade and appear functions ready to add animation on your page. You can download the files from the Bit Pixels' Forums. You can also drop by the forum if you have any queries, suggestions or just to say Hi!

Monday, March 31, 2008

Pixel Pies are served

So I saw this post on Anil Dashes' Blog about how there has been a sudden trend of using pixels as the new pie charts. You can see it in an article by Wired News.


Wired News - Pixel Pie Graph


One very important question he raised was the structure that would be formed by these pixels. Like whether or not we should stack it up vertically or horizontally, randomly or take time to strategically placing each pixel as shown above. Today I made this JS Object that makes such a graph, it vertically stacks all the values. It ended up looking something like this -

Wired News - Pixel Pie Graph


Its just a single object, one page I think, pretty neat. I'll be posting a tutorial on how to make something like this pretty soon.

Friday, March 28, 2008

Pulsating Animation CSS Links

This tutorial will show you how to make a pulsating links without using script.aculo.us or other JS animation libraries. This is only a small thing that CSS can achieve but for other animations like Slide Left etc. then use these libraries only.

By the way if you have any problem during the tutorial you can drop by our Google Group and ask me or the others. You may also download the necessary files, so that you'll follow better.

Let us start with the HTML of the links, this is very basic -



<ul class="links">
<li><a href="#" title="Sample Link">Sample Link</a></li>

<li><a href="#" title="Sample Link">Sample Link</a></li>

<li><a href="#" title="Sample Link">Sample Link</a></li>

<li><a href="#" title="Sample Link">Sample Link</a></li>

<li><a href="#" title="Sample Link">Sample Link</a></li>

</ul>

Also in the head you'll have to include a link to the required CSS file -


<link rel="stylesheet" href="res/ui.css" type="text/css" media="screen"/>


The CSS is very normal too, quite similar to the A List Apart Article on LI Drop Downs. -


ul.links{
list-style: none;
padding: 0;

}
ul.links li a{
display: block;
width: 200px;
height: 10px;
border-left: 6px solid #1958b7;
border-right: 10px solid #2175bc;
background: #2175bc;
padding: 10px 20px;
color: white;
text-decoration: none;
font: 12px sans-serif;
}

ul.links li a:hover{
border-right: 10px solid #508fc4;
background: url('background.gif');
}


This will look something like this -


The actual pulsating effect is caused by the 'background.gif' that will be an animated GIF that has a color-fade between 2 colors. Once we have made it and put it in the /res folder, everything will function as required.

Let us start making it. We'll make a 20X20 px photoshop file. We'll have 2 layers in it one filled with the color #2175bc(dark) and the other layer with #2586d7(light).


Now we switch to ImageReady. We'll be making a simple animation, in which we'll vary the opacity of the light frame from 0% to 100% (in 10 frames) and the back to 0% in 10 frames.


On the top right corner of the layers window, you'll find the option to change the opacity. Remember you have to change the opacity of the the "Light" layer and let the dark layer remain the same.

Start with 0% increment by 10% till it becomes 100% and then back to 0%. Like 0,10,20,30...100,90,80...20,10,0. Also remember to make a new frame for each opacity. The button that'll allow you to make the new frame is located at the toolbar of the Animation window in ImageReady.


Save it as background.gif and you are done. If you wish you can download the HTML, CSS, GIF and the PSD Source file from the BitPixels Forums. You can ask for an help or give suggestions in the forum too. Don't forget to drop by.

Tuesday, March 25, 2008

Pixel Pie Graph Tutorial

Introduction
This tutorial will be teaching you how to make an object in JavaScript that will allow you to make a pixel pie graph. If you don't already know what it is, you read my either my blog post or on Anil Dashes' Blog. You may also see a good example of a pixel pie chart at Wired News. So we will basically try and make a pixel pie chart, something that will end up looking like this -


Pre-requisites
Before actually starting with the coding, I expect you to know very basic JavaScript JavaScript and a bit of DOM. You can go to YUI Theater and look at all the video by Douglas Crockford.

If you have any problem during the tutorial, drop by on our Google Group so that me or any of the other members can sort it out. I also suggest you download the necessary file so that you'll follow better in the rest of the tutorial.


Let's Begin
So as we are going to be making a single object to take care of the whole pixel pie graph, let us take a look at what all it'll be containing.

Object Pixel Graph -
  • data: This will be hash table or JSON that will contain the data that has been submitted by the user. It'll basically have a caption and a value, like "Apples, 50".
  • pData: We will need to convert this data to percentages so that we can easily and efficiently. So we will be putting all the percentage values of our data into this hash table.
  • colors: This'll be an array of colors from which our program will pick the colors for the pixel pie graph. We will be keeping the hex values of the colors in this array.
  • title: Its always nice to have a title to the chart.
  • render(): This function will actually be rendering the table of 100 X 100 where the pixel pie chart will be formed, and fill it with the right colors and values.
  • validateData(): This will be a simple function to take the data and convert it to pData.
Right, now that we know what all we will be making, let us actually start building the object.

Let us start off by making our PixelGraph object and fill it with everything we'll need. Then we'll discuss each function we need.


PixelGraph = {
data: [],
pData: [],
colors: [],
title: "Graph",
render: function() {},
validateData: function() {}
}


We'll fill the functions up later. For now let us make an instance of this object and put some data into it.

fruits = Object(PixelGraph);
fruits.title = "Sales of Fruits in 2008";
fruits.data = [
{
name: "Apple",

value: 450
},{
name: "Mango",

value:2300
},{
name: "Grapes",

value: 3700
},{
name: "Banana",

value: 1000
},
{
name: 'Cherry',

value: 2000
}
];
fruits.render("graph");


So as we see, first we make an object that'll inherit from the PixelGraph, then we put in the title as a string. Then we add the data as an array whose elements are hash tables containing the name or caption and the value as discussed in the basic structure. Then we call the function render and pass the ID of the div in which we would like the graph.

Now, the first function validataData() -


validateData: function() {
this.pData = this.data;

this.total = 0;
for (var i=0; i < this.data.length; i++) {this.total += +this.data[i].value;};

for (var i=0; i < this.pData.length; i++) {

this.pData[i].value = Math.round((+this.pData[i].value / this.total) * 100);

};
}

We see that initially we give pData the same value as data. Then to calculate the total, we run a loop on this.data, that has the data and take the sum of all the values and keep it in the this.total variable. Then we run a loop on this.pData and by using basic mathematics we take out the percentages of all the variables and keep it in this.pData.Simple as that! Now we come to the render() function. This is a lot of code so first please read it carefully and then read the explaination. Here is the code, take a deep breath -


render: function(domId) {
this.validateData();

document.getElementById(domId).innerHTML = "<h2>"+this.title+"</h2><div style='float:left' id='graph-"+domId+"'></div><div style='padding-left: 300px;' id='key-"+domId+"'><h2>Key</h2></div>";

var graphArea = document.getElementById("graph-"+domId);
var html = "<table border='1' cellspacing='0' cellpadding='0'>" ;

for (var i=0; i < 10; i++) {

html += "<tr bordercolor='red'>"
for (var j=1; j < 11; j++) {

html += "<td class='pixel-graph' bordercolor='red' id='pg-p"+((i*10)+j)+"'>&nbsp;</td>";

};
html += "</tr>"
};

html += "</table>";
graphArea.innerHTML += html; //Draw the table

for (i=0; i < this.pData.length; i++) {

document.getElementById("key-"+domId).innerHTML += "<p style=';color:"+this.colors[i]+"'><b>"+this.pData[i].name+"</b> <span id='key-"+i+"'> "+this.pData[i].value+"%</span></p>";

};
old = this.pData;
for (i=1; i < 101; i++) {

for (var p=0; p < old.length; p++) {

if(old[p].value !== 0) {

document.getElementById('pg-p'+i).bgColor = "#"+this.colors[p];

if(old[p].value === 1) {

document.getElementById('pg-p'+i).style.background = "#"+this.colors[p]+" url('res/new.gif') top right";

document.getElementById('pg-p'+i).style.borderTop = "none";

document.getElementById('pg-p'+i).style.borderRight = "none";

document.getElementById('pg-p'+i).innerHTML = "<p style='margin:7px 0px 0px 4px'>"+document.getElementById('key-'+p).innerHTML+"</p>";

}
old[p].value--;
break;

}
};
};
}



Right! If you haven't left the blog by now, lets start. This is where I'd say the fun part is.
  1. Obviously we first call the validateData() function so that we have the pData ready for when it is needed.
  2. Then we take the domID of the div and put a heading in it with the title and two more div's that'll contain the table of pixels and the key respectively.
  3. After that we run a nested loop to get the HTML code of the table that will have 10 rows and 10 columns, with each table cell having an ID of pn. Then we put this HTML into the required DIV.
  4. Now we'll be making another loop, that will be going through our this.pData and making the key. We associate each element of the data with a particular color. For this to function correctly we will have to fill the color array we made earlier filling it with the hex of the color. Something like ["eb088d","edadae","a83e6e", "f47d55", "d04a6f"].
  5. For the actual coloring of the cells we'll be running another set of loops. To understand this imagine you have a few jars of candies, each jar having different amounts of candies, with one jar containing one colored candies. You need to take each candy, jar by jar and put it in a grid of 100 X 100. So every-time you place a candy on the grid, the number of candies in the jar decreases and the number of candies in the grid increases. With that in mind read the last for loop's code again.
  6. We loop through the whole grid in the first loop, we sequentially check the pData to be zero (or the jar empty) and then move on to the next element(jar). Also every-time we color a cell, we decrement that elements value (because we have already taken that candy now and placed it in the grid).
If you wish to see the script in action you can download it from the page on the Bit Pixel Google Group. You can also drop by for any suggestions or doubts relating to the tutorials.

Monday, March 24, 2008

Code Colorizer

This post is not about web code editing tools, or JS libraries that will highlight your code when you put it in the correct class like the one by Dan Webb. But it is actually about something entirely different and useless to some, but very useful to me.

As you know that I have decided to put JS tutorials on this blog. So I needed highlighted ode to be displayed in the posts. I had a few option to show highlighted code on this blog -
  1. Post a picture from TextMate. (But then how will someone copy the code?)
  2. Use CodeHighlighter.js. (Does blogger allow external JS?)
  3. Should I put a span tag individually on the code. (Am I Mad?)
  4. Write a little piece of code that'll use CodeHighlighter.js to add the tags for me on my computer and then copy the code. (Takes too much time)
  5. Google (YES!)


So a quick Google search showed that there is a tool that takes code and returns it highlighted and its HTML. I use to go to the same website to make favicons too, Chami, I used to love this website. Its a bit ugly but very effective and does the dirty work so I like it.

Sunday, March 23, 2008

Pixel Pie Chart - Tutorial

Introduction
This tutorial will be teaching you how to make an object in JavaScript that will allow you to make a pixel pie graph. If you don't already know what it is, you read my either my blog post or on Anil Dashes' Blog. You may also see a good example of a pixel pie chart at Wired News. So we will basically try and make a pixel pie chart, something that will end up looking like this -


Pre-requisites
Before actually starting with the coding, I expect you to know very basic JavaScript JavaScript and a bit of DOM. You can go to YUI Theater and look at all the video by Douglas Crockford.

If you have any problem during the tutorial, drop by on our Google Group so that me or any of the other members can sort it out. I also suggest you download the necessary file so that you'll follow better in the rest of the tutorial.

Let's Begin
So as we are going to be making a single object to take care of the whole pixel pie graph, let us take a look at what all it'll be containing.

Object Pixel Graph -
  • data: This will be hash table or JSON that will contain the data that has been submitted by the user. It'll basically have a caption and a value, like "Apples, 50".
  • pData: We will need to convert this data to percentages so that we can easily and efficiently. So we will be putting all the percentage values of our data into this hash table.
  • colors: This'll be an array of colors from which our program will pick the colors for the pixel pie graph. We will be keeping the hex values of the colors in this array.
  • title: Its always nice to have a title to the chart.
  • render(): This function will actually be rendering the table of 100 X 100 where the pixel pie chart will be formed, and fill it with the right colors and values.
  • validateData(): This will be a simple function to take the data and convert it to pData.
Right, now that we know what all we will be making, let us actually start building the object.

Let us start off by making our PixelGraph object and fill it with everything we'll need. Then we'll discuss each function we need.


PixelGraph = {
data: [],
pData: [],
colors: [],
title: "Graph",
render: function() {},
validateData: function() {}
}


We'll fill the functions up later. For now let us make an instance of this object and put some data into it.

fruits = Object(PixelGraph);
fruits.title = "Sales of Fruits in 2008";
fruits.data = [
{
name: "Apple",

value: 450
},{
name: "Mango",

value:2300
},{
name: "Grapes",

value: 3700
},{
name: "Banana",

value: 1000
},
{
name: 'Cherry',

value: 2000
}
];
fruits.render("graph");


So as we see, first we make an object that'll inherit from the PixelGraph, then we put in the title as a string. Then we add the data as an array whose elements are hash tables containing the name or caption and the value as discussed in the basic structure. Then we call the function render and pass the ID of the div in which we would like the graph.

Now, the first function validataData() -


validateData: function() {
this.pData = this.data;

this.total = 0;
for (var i=0; i < this.data.length; i++) {this.total += +this.data[i].value;};

for (var i=0; i < this.pData.length; i++) {

this.pData[i].value = Math.round((+this.pData[i].value / this.total) * 100);

};
}

We see that initially we give pData the same value as data. Then to calculate the total, we run a loop on this.data, that has the data and take the sum of all the values and keep it in the this.total variable. Then we run a loop on this.pData and by using basic mathematics we take out the percentages of all the variables and keep it in this.pData.Simple as that! Now we come to the render() function. This is a lot of code so first please read it carefully and then read the explaination. Here is the code, take a deep breath -


render: function(domId) {
this.validateData();

document.getElementById(domId).innerHTML = "<h2>"+this.title+"</h2><div style='float:left' id='graph-"+domId+"'></div><div style='padding-left: 300px;' id='key-"+domId+"'><h2>Key</h2></div>";

var graphArea = document.getElementById("graph-"+domId);
var html = "<table border='1' cellspacing='0' cellpadding='0'>" ;

for (var i=0; i < 10; i++) {

html += "<tr bordercolor='red'>"
for (var j=1; j < 11; j++) {

html += "<td class='pixel-graph' bordercolor='red' id='pg-p"+((i*10)+j)+"'>&nbsp;</td>";

};
html += "</tr>"
};

html += "</table>";
graphArea.innerHTML += html; //Draw the table

for (i=0; i < this.pData.length; i++) {

document.getElementById("key-"+domId).innerHTML += "<p style=';color:"+this.colors[i]+"'><b>"+this.pData[i].name+"</b> <span id='key-"+i+"'> "+this.pData[i].value+"%</span></p>";

};
old = this.pData;
for (i=1; i < 101; i++) {

for (var p=0; p < old.length; p++) {

if(old[p].value !== 0) {

document.getElementById('pg-p'+i).bgColor = "#"+this.colors[p];

if(old[p].value === 1) {

document.getElementById('pg-p'+i).style.background = "#"+this.colors[p]+" url('res/new.gif') top right";

document.getElementById('pg-p'+i).style.borderTop = "none";

document.getElementById('pg-p'+i).style.borderRight = "none";

document.getElementById('pg-p'+i).innerHTML = "<p style='margin:7px 0px 0px 4px'>"+document.getElementById('key-'+p).innerHTML+"</p>";

}
old[p].value--;
break;

}
};
};
}



Right! If you haven't left the blog by now, lets start. This is where I'd say the fun part is.
  1. Obviously we first call the validateData() function so that we have the pData ready for when it is needed.
  2. Then we take the domID of the div and put a heading in it with the title and two more div's that'll contain the table of pixels and the key respectively.
  3. After that we run a nested loop to get the HTML code of the table that will have 10 rows and 10 columns, with each table cell having an ID of pn. Then we put this HTML into the required DIV.
  4. Now we'll be making another loop, that will be going through our this.pData and making the key. We associate each element of the data with a particular color. For this to function correctly we will have to fill the color array we made earlier filling it with the hex of the color. Something like ["eb088d","edadae","a83e6e", "f47d55", "d04a6f"].
  5. For the actual coloring of the cells we'll be running another set of loops. To understand this imagine you have a few jars of candies, each jar having different amounts of candies, with one jar containing one colored candies. You need to take each candy, jar by jar and put it in a grid of 100 X 100. So every-time you place a candy on the grid, the number of candies in the jar decreases and the number of candies in the grid increases. With that in mind read the last for loop's code again.
  6. We loop through the whole grid in the first loop, we sequentially check the pData to be zero (or the jar empty) and then move on to the next element(jar). Also every-time we color a cell, we decrement that elements value (because we have already taken that candy now and placed it in the grid).
If you wish to see the script in action you can download it from the page on the Bit Pixel Google Group. You can also drop by for any suggestions or doubts relating to the tutorials.