Monday, December 31, 2012

Add a Background Music (MP3) to your Blogger

Here's the simplest method (HTML/JavaScript Widget/Gadget) I can find:

<object type="application/x-shockwave-flash" data="" width="240" height="20" id="dewplayer" name="dewplayer"> <param name="wmode" value="transparent" /><param name="movie" value="" /> <param name="flashvars" value="mp3=" /> </object>

You need to replace the path to your mp3 in red with the URL of the actual mp3. You can upload the mp3 file to your shared hosting server. Add these codes to the "Content".

Hope you like it!!!

Read More »

Sunday, December 30, 2012

Javascript Mouse Wheel Event Handler

I found several examples online but none of it works 100% as expected. I sort of modified them and came out with the version which works 100% for me on Chrome, IE, Safari and Firefox.

Here it is:

var ff = (navigator.userAgent.indexOf("Firefox") != -1);

if (ff) {
  mousewheelevent = "DOMMouseScroll";
else {
  mousewheelevent = "mousewheel";

if (document.attachEvent) {
  document.attachEvent("on"+mousewheelevent, catchWheel);
else if (document.addEventListener) {
  document.addEventListener(mousewheelevent, catchWheel, false);

function catchWheel(e){

  var evt=window.event || e;
  var delta=evt.detail? evt.detail : evt.wheelDelta/40;
  if (ff) { delta *= -1; } // Firefox gives opposite sign
  if (delta > 0) {
    // Scroll Up detected
    // Handle Scroll Up Event
  else {
    // Scroll Down detected
    // Handle Scroll Down Event


Read More »

The Death of Web Page ...............???

Ever since the social network pages such as Facebook, Twitter and Linked'in came into picture, the demand of conventional web pages are slowing down.

Especially blogs, you'll see less and less new blogs or many blogs are switching over to Facebook pages.

Additionally, with the mobile apps getting more and more popular, web pages take another hit. Web users nowadays prefer Facebook and mobile apps over conventional web pages due to its simplified user interface, easy exposure to friends and very "touching" (AJAX and touchscreen friendly).

Still, I can see the following scenario that will prevent web pages from dying off:

  1. Corporate image - no company can afford to live without a proper web page. For web user without any tablet or smartphone, conventional web pages are still a good source of information.

  2. Versatility - you can put more info on your web page than other mobile platform and social networks. Such as Facebook, you cannot put much info on a Facebook page. You can also hardly put as many info on a mobile app either. For mobile apps, access to info usually goes through a series of touches before you can get to the content you need. The navigation is a bit more complicated.

  3. Exposure - contents in social networks and mobile apps are harder to be found in search engines. If you want your electronic content exposed to public web users, you'll need conventional web pages. Contents in social networks and mobile apps are very limited to their users only.

I could be wrong. The wind may change its direction any time. But I'm confident that web pages still have many years of popularity to come. Imagine those web giants Google, Amazon, Ebay only available on mobile apps, the picture is ugly.

What I can see is expansion rather than contraction. Most organization requires not only a web page nowadays, they also require a presence on social networks and mobile applications. Web developers now need to equip themselves with various skills in order to survive. Due to the current web search capability and incentive to write blogs or online tutorials, keeping up with latest technology or programming skills cannot be easier. Anything you want to learn especially programming, just "Google" for it.

Instead, the current trend is good for web developers. That's only one thing that is holding back the conventional web presence, I discover more and more small businesses and companies are only requesting presence in Facebook and reject conventional web pages. Since Facebook pages can be set up easily, it is a good tool for small organization to save cost which is also something good for them.

In conclusion, the challenge in web development is being taken to a new height, actually closing in to a peak. A web developer is not only required to know the nature of IE5, IE6, IE7, IE8, IE9, IE10, latest Firefox, Chrome, Safari, Opera, Linux based web browsers and all the mobile versions of browsers, they also need to learn to develop apps, developing Facebook pages and applications. It is never this fun for web developers until recently. I think it is time for people like us to hunt for food to grow our hair faster!

Is it the end of web pages? A big NO. Is it a good source of income as a developer? Sadly, a big NO as well as one needs to spend a lot more hours for a fee that is closed to a simple web page 10 years ago. So think twice before you want to become a web developer. :(

P.S.: Don't forgot that mobile apps come in two flavours, iOS and Andoid which requires very different codes and platform. To make the matter worse, you still need to deal with the difference between the screen resolutions especially the difference between the tablet and phone version.

P.S.2.: With the popularity of Facebook, websites are obliged to make it feel "Facebook" which means a lots of "AJAX" toys without refreshing the page.

Read More »

Is It The End of Javascript?

Since almost all of our javascript codes can be replaced by jQuery equivalent, do we still need Javascript?

The answer is yes and no. Yes, if you want to place dynamic HTML content in a controlled page such as Ebay. Ebay doesn't allow the call to an external javascript such as the jQuery library. You have no choice but to switch back to conventional javascript for actions.

For me, I would encourage the use of conventional javascript for beginners. Then switch it to jQuery after learning the basics of dynamic HTML.

There is not much difference between javascript and jQuery in terms of speed. But when it comes to coding, jQuery can save us many lines of codes especially when it comes to traversing down the DOM stucture.

So jQuery or javascript? I think both. First, grasp the basics of javascript and switch to jQuery once you are comfortable with the basics of DOM structure.

Read More »

Tuesday, December 25, 2012

Pre-fill Text Input Box with Grey Text using Javascript

I don't know since when the pre-filled grey text in the text input box becomes so popular. Here's what I do. I hope these are the simplest codes. Enjoy!

The Javascript & HTML:

function checkText(action) {
  if (document.getElementById('myTextID').value == 'Default Text' && action == 'focus') {
    document.getElementById('myTextID').value = "";
  else if (document.getElementById('myTextID').value == '' && action == 'blur') {
    document.getElementById('myTextID').value = "Default Text";
    document.getElementById('myTextID').style.color = '#bbbbbb';
  else {
    document.getElementById('myTextID').style.color = '#333333';
    // You can put more action here such as the AJAX submit codes


<input type=text name=textName size=20 maxlength=100 id=myTextID onFocus="checkText('focus')" onBlur="checkText('blur')">

document.getElementById('myTextID').value = 'Default Text';
document.getElementById('myTextID').style.color = '#bbbbbb';

P.S.: You can change the 'Default Text' to something else.

Read More »

Friday, December 21, 2012

Render Text in PNG Format using PHP GD2 in IIS Environment

The following example won't work if you are running GD version 1 in your PHP server. Some modications are required to make it work.

GD's imagettftext by default cannot set the spacing between characters. If you want to force spacing between characters, you can display each character at a time calculating the spacing your self using a loop.

However, there is one problem setting the spacing: each character's width is different. Therefore, the spacing varies depending on the width of each character.

We use imagettfbbox to measure the width of a character with a given font.

imagettfbbox is troublesome as it is using different requirement to specify the font location in IIS. For Linux environment, you also need to add './' in front of the relative font location. As for IIS, absolute font location is needed. dirname(__FILE__) is used to specify the absolute current script location.

If the font's location is not specified correctly, the error of "Warning: imagettfbbox(): Invalid font filename in ..." will be produced.

Even the location is specified correctly, imagettfbbox gives different result according to the GD version. The following example codes are targeted for GD version 2. If you are using GD version 1, you can modify the codes a bit to make it work.

For imagettfbbox in GD 2 environment, an array of 8 elements are returned. Each data in the array represents a x or y coordinate in the bounding box of a character:

For my case, I use x1 to deduct from x2 to get the width of the character.

Finally, enough said, here are the codes:


// Make sure you have the font arialbd.ttf in the ./font directory

$height = 40;
$width = 80;
$text = "test";
$font_space = 9; // You can change the font space here
$font_size = 19;
$angle = 0;
$x = 10;
$y = $height/2 + 7;
$color = 0; // text color black
$bgcolor = '#ffff00';
$font = 'fonts/arialbd.ttf';
$font2 = './fonts/arialbd.ttf';

$img = imagecreatetruecolor($width, $height);
imagefilledrectangle($img, 0, 0, $width - 1, $height - 1, gd_color($bgcolor));

$textlen = strlen($text);
for ($i = 0; $i < $textlen; $i++) {
 $charwidthArr = imagettfbbox(12, 0, dirname(__FILE__).'\\'.$font, $text[$i]);
 $charwidth = $charwidthArr[2] - $charwidthArr[0];
 imagettftext($img, $font_size, $angle, $x, $y, gd_color($color), $font2, $text[$i]);
 $x += $charwidth + $font_space;

header("Content-Type: image/png");

function gd_color($html_color) {
     return preg_match('/^#?([\dA-F]{6})$/i', $html_color, $rgb)
      ? hexdec($rgb[1]) : false;


Read More »

Sunday, December 16, 2012

Check Out Facebook Friends with Specific Birthday Month FQL

As in my previous post, here's the modified version to list out friends with birthday in the month of May in Facebook.

SELECT name,uid,birthday_date FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2=me()) AND strpos(birthday_date,'05') = 0

You can change the month (highlighted in blue) to some other values.

Read More »

Saturday, December 15, 2012

Check Out Facebook Friends with Most Mutual Friend FQL

As in my previous post, here's the modified version to list out friends with most mutual friends in Facebook.

SELECT name,uid,mutual_friend_count FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2=me()) ORDER BY mutual_friend_count DESC

Read More »

Check Out The Seniors Among your Facebook Friends Using FQL

As we know that we are all assigned an ID as we signed up a Facebook account. The account grows bigger as time goes by. We can tell from this little hint who signed up the FB account earlier by comparing the user ID.

Here's the FQL used to generate the list according to the time first joined the social network:

SELECT name,uid FROM user WHERE uid in (SELECT uid1 FROM friend WHERE uid2=me() ORDER BY uid1 ASC)

As in the earlier post, you can try out this FQL query here:

Read More »

Friday, December 14, 2012

Check Out Facebook Friends with Most Friend FQL

Here's a fun FQL to find out who among your FB friends has the most friends:

SELECT name,friend_count,mutual_friend_count FROM user WHERE uid in (SELECT uid1 FROM friend WHERE uid2=me()) ORDER BY friend_count DESC

Just copy and paste from the above query codes and paste it to:

I also added the mutual_friend_count for more fun. You can add as many objects you want to "query" from the table documentation here:

The Output? Of course, the data in JSON format.

Read More »

Sunday, December 9, 2012

jQuery: Dim an Entity and Hide it

Make sure you call the jQuery library before running any jQuery functions. Either library version is fine, Google or jQuery Foundation. The following shows the code to dim the myDiv to 0.1 opacity within 500ms. After that, hide the DIV:

$('#myDiv').fadeTo(500, 0.1, function() {
  $('#myDiv').css({visibility: "hidden"});

If you straight away animate the opacity to 0 without hiding the DIV, the DIV will stay there although it is not visible nor it is hidden. If the DIV is another layer, it is recommended to hide it or it could cause some interactivity problem as it may cause the links below the DIV not being able to interact with the user.
Read More »

Sunday, August 26, 2012

jQuery toggle() not working?

I just found out that toggle() is not working with the JQuery version I've been using. I am using 1.72 from this link. After switching to version 1.80, I now can lay back a bit by enjoying the convenience of toggle() function which requires many lines of codes if using javascript to control the visibility of an element. Silly me. ;)
Read More »

Tuesday, August 21, 2012

Simple HTML/Javascript Codes to Display your Live Mouse Coordinates (Firefox Fix)

The firefox friendly version:


<script type="text/javascript">

var ff = (navigator.userAgent.indexOf("Firefox") != -1);

function showXY(e)
  if (ff) {
     var s = 'X=' + e.pageX + ' Y=' + e.pageY;
     document.getElementById('coordinates').textContent = s;
  else {
     var s = 'X=' + window.event.clientX + ' Y=' + window.event.clientY;
     document.getElementById('coordinates').innerText = s;

document.onmousemove = showXY;



<div id="coordinates"></div>


Here's the firefox friendly version. Instead of using onmousemove event capture in the body tag, it is initiated in javascript before the body. IF you initiate the event in the body tag, it won't work. A rare Firefox problem with a weird solution. But it works.
Read More »

Monday, August 20, 2012

Simple HTML/Javascript Codes to Display your Live Mouse Coordinates

Here they are:


<script type="text/javascript">

function showXY()
   var s = 'X=' + window.event.clientX + ' Y=' + window.event.clientY;
   document.getElementById('coordinates').innerText = s;


<body onmousemove=showXY()>

<div id="coordinates"></div>


The key component for this to work is highlighted in green. However this won't work in Firefox. The firefox friendly version can be found here. Sorry I wasn't aware of the Firefox problem earlier. Another way to fix this is to use JQuery.
Read More »

Weird Chrome Javascript Problem

I encounter this today that the Javascript var top cannot be used in Chrome. Weird. It works well in Safari and IE. In Chrome, the variable name is stored as [Object Window]. Solution: Just rename top variable to something else.
Read More »

PHP to Replace Last Character in a String

Seems like a trivial code but it's nice to put it here as I tend to forgot the syntax from time to time:

$line = preg_replace("/\n$/","",$line); // To replace last newline character

$line = preg_replace("/\r\n$/","",$line); // To replace last newline character in Windows environment

$line = preg_replace("/\s$/","",$line); // To replace last space in a string

Assuming your string is stored in $line.
Read More »

Sunday, August 5, 2012

Protect Your CSS and Javascript Codes

Update 20th of March 2013: Here's a updated version to include a simple minification before sending your Javascript / CSS codes to the browser especially Chrome:

Actually there is no 100% way to protect your CSS and Javascript codes as if the person who intended to copy is using Google Chrome browser, your codes will be shown no matter how you protect them. But there is a good thing about protecting your CSS and Javascript codes. Google Chrome won't display the comments or 100% your original codes. Your codes will be made conformed to Chrome standard before being displayed. Without the 100% original codes, the intruder won't be able to copy your codes that easily.

Here's how you use Chrome to view any CSS and Javascript:

Simply right click on any webpage

Google Chrome's Inspect Element facility can inspect anything on a web site including your protected CSS and Javascript. Anyway, it is still a good practice to protect your CSS and Javascript if you think your hardwork should be protected and shared only someone asks you nicely for the codes. Here they are in the following.


<link rel="stylesheet" type="text/css" href="mycss.php">
<script language="JavaScript" src="myjs.php"></script>

The PHPs:

For mycss.php:


error_reporting(0); // make sure it is not reporting any warning that will ruin the output
if (preg_match('/',$_SERVER['REMOTE_ADDR'])) {

a {text-decoration:none;color:#777777;}



For myjs.php:


error_reporting(0); // make sure it is not reporting any warning that will ruin the output
if (preg_match('/',$_SERVER['REMOTE_ADDR'])) {

var ie=0;



You can also use $_SERVER['REMOTE_HOST'] if your shared server keeps on changing the IP address. You need to use your Domain Name instead of the (IP Address) above.
Read More »

Saturday, August 4, 2012

Setting Permission for PHP/IIS Environment Especially When PHP Temporary File Facility Is Used

When PHP is run on IIS platform, users will run into the following problems:
  • (A) Files are not able to be written, created, or rewritten on the C:\inetpub\wwwroot\ directory.
  • (B) PHP uploaded temporary file will not be able to be written and this results in file upload problem. For example, $_FILES["FileID"]["tmp_name"] will not be able to be written.
  • (C) PHP tmpfile() command will fail.
In order to solve this problem, permission on the windows directory should be set correctly. For Linux, it's simple. For windows, it's a bit tricky. You can set the permission on IIS/Windows system using these steps:

  1. Go the folder you want the permission changed to IIS/PHP friendly settings. Right click on the folder and select Properties.

  2. Select the Security Tab.

  3. Click on Edit as indicated above. (There's no need to select Group or User at this point)

  4. Refer to the screen capture above, select Users(YourComputerName\Users). Then check the Full Control Allow and then click on Apply.
  5. Repeat Step D above but this time, select IIS_IUSRS(YourComputerName\IIS_IUSRS) (4). Then as in step D, check the Allow for Full Control (2) then Apply (3). Press OK and then OK again.
You now have set a loose permission for IIS/PHP to perform file operations on the folder you just fine-tuned above. My recommendation for the permission settings may be too loose for some. It's more meant for the PC or notebook in which you are only one who can access to the files. Now in order to solve (A)&(B) problem above, you just need to select the target folder to be granted full permission and repeat the steps above. In order to solve problem (C) above (tmpfile() not working), you need you loosen the C:\WINDOWS\Temp permission. As for problem (B), you also need to check out the phpinfo() by adjusting the PHP.ini so that you see where your temporary is:

You can use the search of 'tmp' and you'll find it in the first search result. Then set the php.ini according to your need. You can also set it to C:\WINDOWS\Temp but you need to grant the permission for PHP to store the temporary file here.
Read More »

Sunday, July 15, 2012

Save Your PHP in UTF-8 Format Without BOM

BOM or byte order mark is to indicate the byte order of your file. If your PHP file contains non-English characters, UTF-8 formatted PHP file will display as question mark(?) if the PHP script is run on Linux/Apache web service platform. However, no problem is found on Windows/IIS web servers. You can run the following PHP codes to check whether your PHP got BOM:


$handle = fopen('yourfilename.php','r');
$bom = fread($handle, 3);

if (empty($bom)) {
else if ($bom === chr(0xef).chr(0xbb).chr(0xbf)) {
 // UTF8 Byte Order Mark present
else {
 echo("No BOM");


If you see BOM in your UTF-8 PHP file, you'll need to convert to non-BOM format. You can easily fix it by editing using Notepad++. After opening your BOM PHP file, go to the "Encoding" menu and choose "Encode in UTF-8 without BOM". Then save the file.

Your PHP can now output non-English texts without any problem!

P.S.: (update on 18th of July 2012) You need to upload to the server as ASCII formatted file. I missed out this important info earlier. Sorry.

Read More »

Adding PHPExcel PEAR Library in Shared Hosting Environment

You need to have the PEAR library installed in your shared host/server before this. If you haven't done so, you can check out my earlier post on how to do this.

The Steps I used:
  1. You can download the PHPExcel here. Choose the PEAR version. As of now, the current version is 1.77 and the file size for the .tgz file is 11.7MB.

  2. Extract the .tgz file. You'll see a PHPExcel.php and a PHPExcel folder. Like other PEAR add-ons, you just need to copy the PHP file and the folder to your PEAR root directory. You can find out the root directory during the installation of PEAR. You can also refer to my earlier post on this.

  3. Upload the above mentioned PHP file and its folder to your shared server.

  4. Test your PEAR PHPExcel library using the following codes:


    set_include_path('./RELATIVE_PATH_TO_YOUR/PEAR/' . PATH_SEPARATOR . get_include_path());

    $excel = new PHPExcel();
    $excel->setActiveSheetIndex(0); // select a worksheet
    $excel->getActiveSheet()->setTitle('Products'); // name the sheet
    $excel->getActiveSheet()->setCellValue('A1', 'Orange');
    $excel->getActiveSheet()->setCellValue('A2', '1.30');
    $excel->getActiveSheet()->setCellValue('B1', 'Apple');
    $excel->getActiveSheet()->setCellValue('B2', '2.10');
    $excel->getActiveSheet()->setCellValue('C1', 'Total');
    $excel->getActiveSheet()->setCellValue('C2', '=SUM(A2:B2)');

    // Save document in the Excel 2007 format
    $excelWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
    echo("Products.xlsx created!");


  5. Open the "Products.xlsx" with Excel to see if the xlsx file is fine as planned.

Note: If your PHP file above (to test the PHPExcel library), contains non-English character, you'll need to save it in non-BOM format preferably saved using Notepad++. Here's my post to address this fix.

As for the RELATIVE_PATH_TO_YOUR in red above, RELATIVE is the key. If you PHP file is in a subdirectory and your PEAR's root is in another subdirectory, you need to find a path to refer to PEAR. For example, if your testPHPExcel.php is in the /test directory and your PEAR is in /PEAR directory, you'll need this relative path such as ./../PEAR/.

You are done here! Enjoy!
Read More »

Install PEAR for Shared Hosting

PEAR is undeniably a good source of PHP code library that will make programmers' life a lot easier. Installing PEAR on Windows/IIS platform is easy especially when you have admin access to your PC/server.

When it comes installing PEAR in a shared hosting environment, admin access is null and there are workarounds that need to be addressed in order to use the PEAR library in the restricted platform.

Here are the steps I use:

  1. Go to
    Copy the content and save it as go-pear.php or other names that you prefer

  2. Upload the go-pear.php to your server and launch the PHP codes by browsing the php such as logging on to http://yourdomain/yourpath/go-pear.php

  3. During setup, you need to find out the path of your PHP executable. You can easily find out by running a PHP like this:

    echo `which php`;
    // or echo PHP_BIN if this doesn't work;

  4. After the installation is done, you can now remove the go-pear.php for security reason. You will also be given the absolute path to your PEAR here.

    Note: To use PEAR without any problems you need to add your PEAR Installation path (/xxxxxx/xxxxxxxx/xxxxxxx/......./PEAR) to your include_path.

  5. Test your PEAR. You can try the following simple PHP code:


    set_include_path('./PATH_TO_YOUR/PEAR/' . PATH_SEPARATOR
    . get_include_path());

    require_once 'PEAR.php';

    If it returns a bool(true), you are all set. Enjoy! :)

    Note: You need to make sure the include path is there every time you need PEAR. This is for shared hosting environment. If you have admin access, you can easily skip this by adjusting the PHP.ini file.
Read More »

Tuesday, February 7, 2012

Image (<IMG>) SRC Dynamic Update Using Script Not Working in IE

If you have HTML code running this dynamically changing image:





<img src="myscript" id=myID>

This won't work in IE. You need this:


var randomNo=Math.floor(Math.random()*10000);



As IE will refer to cache data if it sees the data is the same as the next click.
You can also change to other methods of generating random numbers. As long as the query string is different every time, IE will not refer to cache data and fetch from the server instead.
Read More »

Tuesday, January 3, 2012

Chrome/Firefox/Safari Not Able to Read External Javascript/CSS

This is something a web programmer needs to take note as this could lengthen your coding time if this is not taken into account.

Chrome/Firefox/Safari is not able to read external Javascript/CSS with commands such as:

<link rel="stylesheet" type="text/css" href="testcss.php" />
<script language="JavaScript" src="testjs.php"></script>

if your broswer runs in STANDARD mode (with the declaration of DOCTYPE).


1) Include your CSS/JAVASCRIPT in your HTML file that you are running, to prevent referring to an external CSS/JAVASCRIPT

2) Run your browser in QUIRK mode (do not declare any DOCTYPE)

3) Use PHP to spit out DOCTYPE if IE browsers are detected

I would put codes like these before the <HTML> in my whatever.php:

error_reporting(0); // This is needed if your PHP spits errors/warnings to your browser
if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
echo('<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">');
Read More »

iFrame Transparency Problem in IE and Solution

With the default setting, IE sets the background color of a HTML body to white if no value is set.

For other browsers, the background color is set to transparent by default.

In order to make IE iframe HTML to accept transparency, one has to set both the iFrame and HTML body value correctly.

The iFrame:

<iframe src="dummy.html" width=400 height=400 allowtransparency="true">

Inside dummy.html:

<body style="background-color:transparent">

Well, that's the fix for IE. Just two small steps.

Yes, this is my 2nd post in 2012. Happy belated New Year!!!
Read More »

Monday, January 2, 2012

Chrome and setTimeout() Javascript Function

I once made the O capital letter and it won't work in Chrome.

setTimeout() - OK
setTimeOut() - Not working in Chrome

Just a trivial post but it is interesting.
Read More »