Friday, October 24, 2008

JavaScript for applying event for specific class of HTML Elements

Hi,

Commonly, when we apply event for an HTML Element, we are going to create a function first then put it to function attribute to the html element, in order to trigger the event. Example of this: Assumed that you created a function named PopupHello() that will simply display an alert box with the world "hello" on it. Traditionally, in order to trigger the event, you will put this function inside
the function attribute of a specific html element:
<a href='javascript:void(0)' onclick='PopupHello()'>


That's fine, it works well. But, what if you have the same element in different pages that will do the same function. So, you will have to put the onclick='PopupHello()' for each element, which is for me, it's inappropriate and is costly, because it will add an additional size to your hard drive (or anywhere else..) everytime you add the same element.

Solution for that, is to add a class name for each element that has the same functionality, and during the loading of your website, get all the elements with the same class name and add the function to that class name. I provide the code below to show you how it's done. Just read the comments to understand how it works.

The Code:


<html>
<head>
<script type='text/javascript' language='javascript'>

//this function will get all elements
//in a specific tag passed to this
//if * is passed, it means all the tags
//inside the html
function getDocumentElements(tag)
{
return document.getElementsByTagName(tag);
}


//this is the function that will assign a specific function
//to the click function of a tag within the class
function assignFunction(paramTag, paramClass, paramFunctionName)
{
//first, is to get the elements under a tag
//passed "*" to get all elements regardless what tag
var docElements = getDocumentElements(paramTag);

//loop through each element
for(var i=0; i < docElements.length; i++)
{
//check if the element is under the specific class
if(docElements[i].className == paramClass)
//add the function to the onclick event of the element
docElements[i].onclick = function() {
//this will trigger when this element is clicked
var func = new Function(paramFunctionName);
func();
};
}

}

function PopupHello()
{
window.alert('Hello');
}

function doB()
{
window.alert('Event coming from Class B element');
}

//during window loads
window.onload = function() {
//assign PopupHello() function to any elements
//that belongs to class classA
assignFunction("*","classA", "PopupHello()");

//assign doB() function to anchor elemens (anchor tag <a>)
//that belongs to class classB
assignFunction("a","classB", "doB()");
}
</script>

<title>JavaScript</title>
</head>

<body>

<img class='classA' src='imgA.gif' alt='Class A Image'/> <br /><br />


<img class='classB' src='imgB.gif' alt='Class B Image' /><br />

<a class='classA' href='javascript:void(0)'>Class A - anchor tag</a> <br />
<a class='classB' href='javascript:void(0)'>Class B - anchor tag</a> <br />
<span class='classA'>Class A - span tag</span> <br />
<a class='classC' href='javascript:void(0)'>Class C - anchor tag</a>
</body>
</html>


All elements under class classA will display an alert box saying 'hello'.

classB elements will alert 'Event coming from Class B element'.
And classC will do nothing.

If you will add new element, for example an another anchor tag for classA. You will
simply put the attribute class then attribute value to classA (hence, class="classA").

And, if you want to add a clicked event for other element like for example class classC then anchor tag.
Simply put this inside the onload function: assignFunction("*","classC", "NameOfFunctionForClassC()");

That's all. Thank you.

-Jygz
jjygot@gmail.com

Wednesday, October 22, 2008

How to use the while loop using sql server

How to use the while loop using sql server

To start with the discussion we need a counter variable with an int DataType that would define the limit to where the loop will stop. In my case I named my counter variable as TotalMonths and
assigned it with a value of 12.

Declare @TotalMonths as int
set @TotalMonths = 12

-- The While statement is almost the same as the usual programming
-- concept for the while statement. All we need is the logic as to how the
-- loop takes place.
-- In my case I wanted to begin my loop by stating that TotalMonths should be
-- greater than zero before it executes the loop..

While @TotalMonths>0

-- We need to have the begin and end statement after the condition in order to
-- set the scope of the while loop. Hence, if we try to remove the begin/end in the loop,
-- we will notice that the query will have an infinite loop.
begin
-- Here we create the statement that we wanted to do if the condition of the
-- while statement is true.
print datename(mm,(dateadd(mm,-@TotalMonths,(1))))

-- The most important thing on the while loop, is to create a loop iterator to avoid
-- infinite loops.
set @TotalMonths = @TotalMonths - 1
end

Script:
Declare @TotalMonths as int
set @TotalMonths = 12

While @TotalMonths>0
begin
print datename(mm,(dateadd(mm,-@TotalMonths,(1))))
set @TotalMonths = @TotalMonths - 1
end


This results:

January
February
March
April
May
June
July
August
September
October
November
December

.Net Equivalent of PHP's implode and explode function

Hi,

Lots of developers from PHP who study/migrate to ASP.Net have problems figuring out how would they implode an array of strings, or explode a string to array. Like me, this situation came out during my study in ASP.Net, I wondered what was the equivalent of PHP implode and explode function in .Net. And then I found out, that in .Net you can achieve this using the .Net's built-in string functions: Join function for implode, and string Split function for explode. To illustrate more, I make a sample code as shown below:

Type rest of the post here

///Assumed that you have two labels for display: lblColors, lblFruits
//****IMPLODE/JOIN****\\
//sample string of colors
string[] arrColors = {"red","orange","yellow","green","blue","indigo","violet"};

//implode/join the colors array using "and" and store it to a string variable
string strImplodedColors = String.Join(" and ", arrColors);
//display the imploded/joined to the colors label
this.lblColors.Text = "The colors of the rainbow are: " + strImplodedColors;


//****EXPLODE/SPLIT****\\
//sample string for comma-separated fruits
string strFruits = "avocado, apple, mango, grapes, banana";
//separator for the string
char[] separator = {','};
//explode/split the string and store it to a string array
string[] arrFruits = strFruits.Split(separator);
string strFavFruitDisplay = "Below are my top favorite fruits:
";
int i = 1;//iterator for counting display
//loop or iterate for each string in the exploded string
foreach(string strFruit in arrFruits)
{
//add each fruit to the display string
strFavFruitDisplay += i.ToString() + ". " + strFruit + "
";
i++;
}
//display the favorite fruits
this.lblFruits.Text = strFavFruitDisplay;

The above code is C#, if you want a VB version of it, just go to this URL: http://www.developerfusion.com/tools/convert/csharp-to-vb/

copy the code and convert it. It will allow you to easily convert C#.Net codes to VB.Net and vice versa.

Try it!

jjygot@gmail.com

Better JavaScript for Numeric Only Input in text box

Hi,

Sometimes, you will meet a scenario where you will just allow the user to input only numbers in a text field in your web page.
Examples are:
1. text field for quantity of a product to be purchased
2. text field for order number.... and more



Although, this can be done in the server-side process, but it's much better to do this in the client side (like checking if the key pressed is a number) for better user-experience. Because doing this in the server side will reload your page back and cost time and process. Doing this in the client side, is more user-friendly, there is an immediate checking, everytime the user presses a key in the keyboard the client javascript will check if that key is a valid number without interrupting the user on what he/she's doing.

To achieve this, we are going to create a JavaScript function then apply it to our text field.

Assumed that we have the following html code(pure html):

<html>
<head>
<title>Numeric Only in Text Input</title>
</head>
<body>
<form>
Enter Number: <input type='text' />
<form>

</body>
</html>


What To Do:

1. Place the following code: inside the head tag of your html


< script type='text/javacript' language='javascript'>
//function for allowing numeric only
function NumericOnly(e)
{

//gets the numeric code of the key pressed
var charCode = (e.which) ? e.which : e.keyCode

//checks if the cod is greater than 31 like the "space" which is 32,
//and it is less than 48 which is "0" or greater than "57" which is 9
//then do not allow it

if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;//key pressed is not allowed

return true;//key pressed is allowed
}

</script>




2. Apply the function to the key press event of the text field you want to allow numeric only inputs.
thus:
<input type='text' onkeypress='return NumericOnly(event);' />



Final Output:

<html>
<head>
<script type='text/javascript' language='javascript'>

//function for allowing numeric only
function NumericOnly(e)
{
//gets the numeric code of the key pressed
var charCode = (e.which) ? e.which : e.keyCode

//checks if the cod is greater than 31 like the "space" which is 32,
//and it is less than 48 which is "0" or greater than "57" which is 9
//then do not allow it

if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;//key pressed is not allowed

return true;//key pressed is allowed
}

</script>


<title>JavaScript's Numeric Only in Text Input</title>
</head>
<body>

<form>
Enter Number: <input type='text' onkeypress='return NumericOnly(event);' />
</form>
</body>
</html>





The key part in the code is :
if (charCode > 31 && (charCode <> 57))

What it does are:

1. It will disallow input which is not valid, it only allows numeric code less than 31( that includes: backspace, enter, arrow keys, delete key, function keys, tabs,...)

2. It only allows numeric code not less than 48 and not greater than 57, less than 48 codes are ( the symbols or operators like +, -, / *, &......), codes greater than 57 are the (special characters like colon:, semicolon;, <,=,?,{,},~.....) , alpha characters(ABCD....abcd...)

Numbers numeric codes range from 48 - 57.

Visit this website to understand more: http://ascii-table.com/

That's all! Try it now...

Have a nice day.

Jygz
jjygot@gmail.com

Monday, October 20, 2008

Flash Image Loader (Action Script 2)

Simple Image Loading in Flash courtesy of Liam J Rutherford

Click here to view sample

Here's the code:
//ImageLoader Function - Liamr.com/blog/?p=86
--Load in TweenLite
import gs.TweenLite;
import gs.TweenFilterLite;
import mx.transitions.easing.*
--Preview Button
preview_btn.onRelease = function(){
loadImage("http://www.liamr.com/labs/source/imageLoader/images/image_1.jpg");

}
preview_resize_btn.onRelease = function(){
loadImage("http://www.liamr.com/labs/source/imageLoader/images/image_2.jpg");
}
//Load function
function loadImage(source:String):Void{

var frameSize:Number = 10;
var frameColor:String = "0x000000";
var frameAlpha:Number = 95;
var mclLoader:MovieClipLoader = new MovieClipLoader ();
var mediaPoplistener:Object = new Object ();

mediaPop.holder._alpha = 0;

mclLoader.addListener (mediaPoplistener);
mclLoader.loadClip(source, mediaPop.holder);

TweenLite.to(mediaPop.bg, 0, {_y:0, _x:0, _alpha:50, _width:Number(Stage.width), _height:Number(Stage.height), ease:Strong.easeOut});
TweenLite.to(mediaPop.frame, 1, {_alpha:50, tint:frameColor, _height:20, _width:80, ease:Strong.easeOut});
TweenLite.to(mediaPop.loader, 0.1, {_alpha:50});
TweenLite.to(mediaPop, 1, {autoAlpha:100});
mediaPoplistener.onLoadProgress = function (target:MovieClip, loadedBytes:Number, totalBytes:Number):Void {
TweenLite.to(mediaPop.loader, 0.1, {_alpha:50});
percentageLoaded = Math.round(loadedBytes/totalBytes * 100);
mediaPop.loader.loadertext_txt.text = "Loading " + Math.floor(percentageLoaded) + "%";}

mediaPoplistener.onLoadInit = function (target:MovieClip):Void {
mediaW = Math.round(mediaPop.holder._width);
mediaH = Math.round(mediaPop.holder._height);
frameW = mediaW + Number(frameSize*2);
frameH = mediaH + Number(frameSize*2);
TweenLite.to(mediaPop.loader, 1, {_alpha:0, ease:Strong.easeOut});
TweenLite.to(mediaPop.frame, 1, {_x:0, _y:0, _width:Number(frameW), _height:Number(frameH), tint:frameColor, ease:Strong.easeOut});
TweenLite.to(mediaPop.frame, 1, {_alpha:frameAlpha, delay:1, overwrite:false});
mediaPop.holder._x = frameSize;
mediaPop.holder._y = frameSize;
TweenLite.to(mediaPop.holder, 1, {_alpha:100, overwrite:false, delay:2, ease:Strong.easeOut});
}
}

Download Source