Wednesday, March 17, 2010

Best Way to Round Up Numbers Using Javascript

I previously found several solutions to round up (float) numbers to closest two decimal places. Some are using complicated function with sofisticated codes but I find this one-liner quite effective and efficient:

Math.round(num*100)/100; // for two decimal places
Math.round(num*1000)/1000; // for three decimal places
.
.

I appreciate the author who did this and sorry for forgetting where I get it from.
Read More »

Tuesday, March 16, 2010

Firefox isn’t Foxy When it comes to Javascript Execution

Strangely, Firefox executes Javascripts the slowest compared to IE, Safari and Chrome. It is a strange phenomenon as it doesn’t affect IE, Safari or Chrome.

There is also a claim that Firefox 3.5 or higher can run Javascript faster. Since there are still many who are using Firefox 3.0 or lower, I will stick to it unless 3.0 has been forced to phase off.

No real fix can be found yet unless to upgrade to version 3.5 or higher which is not a good solution. I cannot just ask all the visitors of the websites I built to upgrade their Firefox. This is a shortcoming of older version of Firefox. Never expect Firefox to have such a small problem that may seem big for someone.
Another thing is to reduce the usage of Ajax as it could slow it down further.

Update (April 4th, 2016): Firefox is no longer the slowest. IE7 or below is the slowest to run Javascript for now. All latest browsers can now run Javascript efficiently. The problem now occurs in tablets. iPad or Android based tablets are now having some speed issues with Javascript even though the specification of the device is encouraging to run heavy tasks. Maybe Javascript is just not their cup of tea.
Read More »

Monday, March 15, 2010

Onmouseover/Onmouseout Event Trap Trick

If you happen to need to do a mouse trap on certain link in HTML, you will use onmouseover and onmouseout to due with it. There is one way to save the onmouseout event trap to simplify the procedure. It is to define a fixed property to it such as the color of a table, the color of a border or even a background image. In that case, during a onmouseout event, the browser will go back to your original fixed settings. But if you purposely define how to due with it during a onmouseout event, it will still take your orders but it is redundant unless you want to change it to something else other than the original initial setting such as making the column blue and border red, etc.

In conclusion, you don’t really need a onmouseout event to change the color. Use the 'hover' feature in CSS instead.
Read More »

Sunday, March 14, 2010

Firefox Pointer Change Problem Using Javascript in <MAP>

If you are using <MAP> and you want to do a onmouseover event trap to change the mouse cursor to ‘pointer’, it won’t work in Firefox but still good for the rest, viz., IE, Chrome and Safari. I didn’t it on Opera though.

Firefox requires at least a hyperlink anchor, viz., <a href=…> to change the cursor to pointer whenever the mouse it on top of the defined area.

Good news is that this is the workaround. Bad news is that for firefox, you can only change it to ‘pointer’ type cursor and nothing else.
Read More »

Saturday, March 13, 2010

MySQL Problem with Japanese/UTF-8 texts

If you have tried to put Japanese or UTF-8 texts in MySQL, chances are it will show “junky” characters after you save/reopen it. An adjustment is needed to fix this simple problem:

Declare the data type as VarBinary. Problem solved.
I’ve tried changing the character set to UTF-8, using the “mysql_enable_utf8=1” setting, making SQL query like “SET CHARACTER SET utf8_unicode_ci;”, nothing seems working. Anyway the simple solution above solved the problem. I have tried it with MySQL 5.x.

Pitfall: If you are using SQLyog as your MySQL manager, you need to use version 6 of above to get it work. Anything less will not work even if you declare the data type as VarBinary.
Read More »

Friday, March 12, 2010

IE Text <INPUT> Minimum Width Problem

If you happen to specify the “size” in the text input form using <input> which is less than 10, chances are the size will be “fixed” to around 10 even if you specify a lower number. In order to solve this peculiar problem of IE or maybe Firefox or Chrome, I have tried the following CSS declaration and it works:

table-layout: fixed;

Strangely, only Safari works well without this fix. Firefox and Chrome can’t even work well using this fix. But at least IE doesn’t have this problem after this fix.
Read More »

Thursday, March 11, 2010

Paypal Login Window Set to Other Languages (Japanese) by Default

I was requested by a Japanese customer to set the default login window in Japanese. I have tried setting the lc (locale) query string to “JP”, it just works half way with English and Japanese as the choices. But Japanese was treated as second language in the locale of “JP”. The default page is still English. Then I tried all the funny things and eventually this works out right:

<input type=hidden name="locale.x" value="ja_JP">

Now the default Paypal login page is in Japanese! But of course this also needs to work with proper locale setting:

<input type=hidden name="lc" value="JP">
Read More »

Wednesday, March 10, 2010

Fixing PERL script saved in UTF-8 Format using Notepad

If your PERL script needs to display non-English texts, say Japanese or Chinese, usually you will save your script in UTF-8 format. Problem arises if you are using Notepad to save the UTF-8 format as it adds the BOM (Byte Order Mark) header to the file.

The problem is that PERL won’t run the UTF-8 file with BOM header once it is uploaded to the server. However, it will run fine if you are running with later version of Apache locally using your Windows based PC.
To solve this problem (if you are not running locally with latest Apache), the following is a PERL script to rid of the first three bytes (BOM header) of the UTF-8 file saved using notepad:

#!c:\perl\bin\perl.exe #or use path to your perl executable
$input = “myfile.pl”;
$output = “myfile_utf8.pl”;
print "Content-type: text/html\n\n";
binmode(STDIN);
binmode(STDOUT, ":utf8");
open(IN, "$input");
@ALL = <IN>;
close(IN);
$all = join("",@ALL);
$BOM_removed = substr $all, 3;
open(OUT, ">$output");
print OUT $BOM_removed;
close(IN);
print “Conversion done! File is output to $output.”;

You can assign $input and $output variables to the file names you desire. These PERL codes can be saved in normal ANSI format.

After the conversion, if the output file doesn’t contain any non-English characters, Notepad will assume it is a ANSI file. Don’t worry. Try to put some non-English characters in your $input file and run this conversion, the $output file will show up as UTF-8 file using Notepad (when you do a Save As…, you will see the format).

Upload the $output file to your server using ASCII transfer mode (not Binary mode), your $output file will run without any Internal Server Error message after chmod (change file permission) $output file to 755.

Please also make sure your $input/$output PERL script prints "Content-type: text/html; charset=utf-8\n\n" HTML header for proper UTF-8 content output.


Note: Do not save the $output file again with notepad, it will lose its "charm". :)
Read More »

Tuesday, March 9, 2010

Redirect a URL inside a frame to a _top page

It’s easy to redirect a URL if you don’t care whether you are from inside a frame or to its own frame using META redirection or window.location javascript redirection.
What if your HTML is inside a frame calling to redirect itself to a _top page? Tricky?

I use this:

if (document.referrer.indexOf('YourAliasName') != -1) {
   top.location.href='http://www.YourMainDomainName.com';
}

You can substitute YourAliasName with a portion of your domain alias name so that the redirection won’t go into infinite loop.

I needed this because my hosting company enclosed my domain alias inside a frame and I need to redirect the domain alias to the main domain name so that it is like a normal redirection without being redirected back inside the frame. Therefore the code above that is highlighted in red is important to move the redirected page to the _top page level.
Read More »

Monday, March 8, 2010

Use Javascipt to change the <select> Pre-select Item

I use this to change:

document.getElementById('idname').selectedIndex = 0;

Tested to work fine with latest IE, Firefox, Safari and Chrome. Your <select> also needs to address the id name such as:

<select id=idname>

You can change the selectedIndex to something else. 0 means the first selection, 1 means the second, etc.
Read More »

Sunday, March 7, 2010

Assigning SetTimeout/SetInterval Functions with Argument(s)

If Javascipt’s SetTimeout()/SetInterval() is assigned with a function that contains argument, it won’t run. After trials and errors, here’s the way that works well with latest version of IE, Firefox, Safari and Chrome:

setInterval(function(){function_name(argument)}, 1000);

Noted those highlighted in red is a function to call another function. I have tried using eval(), it works well in Firefox but it won’t in IE. This trick is to make sure it works with all type of browsers. Using common sense, one may resort to “setInterval(function_name(argument), 1000);”, but it won’t run.

Update 2012 January 14: Please don't put quotation marks around the function.
Read More »

Saturday, March 6, 2010

Calling a Function in iframe

I mentioned how I call a function from iframe. Now I explain how I do the opposite, calling a function in iframe from the parent or main HTML.

After trying a few suggestions found using Google, I find this working for all the browers I use, viz., IE, Firefox, Safari and Chrome:

document.getElementById('framename').contentWindow.functioname(argument);

You can replace your own framename, functionname and argument.





Update: It will not work on Chrome if you are running in local host due to security reason. Upload to a web server and it will work.
Read More »

Friday, March 5, 2010

Paypal doesn’t like to be framed in IE

I tried to redirect a shopping cart form to an iframe a while ago but the Paypal keeps showing an Error something like "your last action could not be completed" while using IE but it works fine in Firefox, Safari and Chrome.

Then I make the redirection to a brand new page by adding the "target = _top" to the link anchor and everything works fine now.

Weird problem. Obviously Paypal doesn't like us to enclose it in a frame.


September 2011 Update: Now Paypal doesn't allow its content to be framed across all browser platforms. Previously it will automatically move the content to the _top page by doing a refresh but now we have to redirect to a new top page ourselves or we'll get a blank page. This is for Paypal standard checkout using HTML redirection. Do we foresee a mandatory SSL redirection in the future?
Read More »

Thursday, March 4, 2010

Speeding up Firefox

I notice HTML content will be a bit slow to show up on Firefox whenever there is an error reported in Firefox Error Console.


As a responsible web developer, it is our duty to run the Error Console every now and then.

Just clear the history and have a run of Error Console and reload of target website, all the problems with the Firefox will show up. Fixing some problems in Firefox platform could fix the speed problem in other browsers as well. So start screening with Firefox’s Error Console today!

Sometimes, Firefox just gives warning. It’s also good to get rid of the warning as it may slow down the browser by performing debugging on the javascript and/or CSS. Sometimes we also need to do some tricks with the HTML so that those properties that are not supported in Firefox are filtered before an official web presence.
Update (April 5th, 2016): I now use Google Chrome's Inspect Element to check for errors as it is more versatile and accurate in terms of reporting errors.
Read More »

Wednesday, March 3, 2010

Firefox is responding slow on Javascript’s onresize()

Compared to IE, Safari and Chrome, Firefox is the slowest in response to the onresize usually put in the <body> tag.


I was testing this using the latest Firefox version and am not sure how the older versions did. I make my HTML to call a function to relocate an object whenever there is a resize event on the browser’s window. Something interesting for developers to pay attention to. If your onresize() is responding slowly to resize events, chances are you are using Firefox 3 and above. Try to test with IE, Safari or Chrome.
Read More »

Tuesday, March 2, 2010

Diplaying Server Date Using PERL and Javascript

I only find PHP solution after googling around, but I wanted to use PERL. Here’s how I did it:


PERL side:

#!/usr/bin/perl

$time = localtime(time);
print "Content-type: text/html\n\n";
print "var serverdate='$time';";
exit;


Javascript side:

<script language="JavaScript" src="/cgi-bin/getservertime"></script>
<script type="text/javascript">
<!--
document.getElementById('time').innerHTML = '<font face=tahoma size=1>'+serverdate+'</font>';
//-->
</script>




Please place a <div id=”time”> </div> somewhere in the your HTML body to receive the server date from this javascript. The PERL script name is getservertime and you can change accordingly if you like.
Read More »

Monday, March 1, 2010

Get the same Browser’s width value across all Browser types

Firefox, Safari and Chrome have almost the same way to measure the page width of the browser window except IE.


This is due to the fact that IE is using different way to get the width of the window than Firefox/Safari/Chrome.


IE uses “window.innerWidth” property whereas Firefox/Safari/Chrome uses “document.documentElement.clientWidth” to get the width of the browser.


The problem now is that IE tends to include the width of the scrollbar where around 15-18 pixels are added to the sum.


I use a simple javascript coding to make sure all the browsers get the same width:



var ie=0;

var agt=navigator.userAgent.toLowerCase();

if(agt.indexOf('ie')!=-1){ie=1;}

pgwidth = getWidth(); // Please find this getWidth() function elsewhere as it is not written by me and it is not right to post here

if (!ie) { pgwidth = pgwidth - 18; }




Now the pgwidth variable carries almost the same width across all common browsers such as IE, Firefox, Safari and Chrome.
Read More »