Saturday, September 7, 2013

Latest Method to Change Facebook Like Box Border Color

As of today, this method still works. This may not work in the future as Facebook changes its support every now and then.

Anyway, here are the codes:


The CSS:
.fb-like-box {
  width: 348px;
  height: 248px;
  overflow: hidden;
  position: relative;
  border: 1px solid #dddddd;
}

.fb-like-box .dummyBox {
  margin: -1px 0 0 -1px;
  border: 0px;
}


The HTML:
<div class="fb-like-box">
<div class="dummyBox">
<fb:like-box width="350" height="250" colorscheme="light" show_faces="true" stream="false" header="false"><iframe width="350px" height="250px" frameborder="0" allowtransparency="true" scrolling="no" title="fb:like_box Facebook Social Plugin" src="http://www.facebook.com/plugins/like_box.php?color_scheme=light&amp;header=false&amp;href=http%3A%2F%2Fwww.facebook.com%2Fpages%2F[Your FB Page Path]&amp;locale=en_US&amp;show_faces=true&amp;stream=false&amp;width=350&amp;height=250" style="border: none; visibility: visible; width: 350px; height: 250px;"></iframe>
</div>
</div>



Those in red are the ones you might want to change according to your preference. Those in green are the important settings to pay special attention to and also the locations where the magic comes from. Basically it is to enclose the FB iframe with two DIVs. One is to enclose to FB iframe with purposely 1 pixel smaller on each side to cover up the original FB like box border. The 2nd DIV is to shift the other DIV to upper left hand corder by 1 pixel using "margin: -1px 0 0 -1px;".

Hope you like this little trick. Enjoy!

Read More »

Friday, September 6, 2013

Javascript to Sniff Android Based Browsers


Updated on 7th of February, 2014: The is_touch_device() function in the following is no longer working. Please check out my latest is_touch_device() function that works in the latest Chrome browser (Nevertheless, the rest of the codes are still working. Just replace the latest is_touch_device() function will do):

http://webtrick101.blogspot.com/2014/02/detecting-browsers-touch-capability.html



Using Javascript to sniff out Android based broswer is tough as the list of Android devices is very lengthy. Here's my Javascript way of performing the Android sniffing task.

<script>

function is_touch_device() {
 try {
  document.createEvent("TouchEvent");
  return true;
 }
 catch (e) {
  return false;
 }
}

var ie = (navigator.userAgent.indexOf("MSIE") != -1);
var ipad = (navigator.userAgent.indexOf("iPad") != -1);
var iphone = (navigator.userAgent.indexOf("iPhone") != -1);
var bb = (navigator.userAgent.indexOf("BlackBerry") != -1);
var touch = is_touch_device();
var android = touch && !ipad && !iphone && !bb && !ie;

if (android) {
 alert("Hello Droid!");
}

</script>


The logic? A touch capable device which is not either iPad, iPhone, Blackberry, or Windows 8 (touch screen), chance is very high that it is an Android device. But the trend will keep on changing. This should be still good for now.

Read More »

Setting Cookie via Javascript Not Working for my Android 2.33 Gingerbread Device

I believe the current Android based device won't have this issue. But it happened to my antique Android Gingerbread based phone. After plenty of testings, here is my conclusion:

Javascript with Problem:
document.cookie = "apple = orange;";


Javascript that worked on my phone:
document.cookie = "apple=orange;";



Very unexpected problem. Simple and unexpected solution as well.

Now I kind of like this name of Android version: Froyo (2.2–2.2.3) if you know what I mean. :)

Read More »

Thursday, September 5, 2013

When DOM marginLeft property is not working in Mobile tablets such as iPad and Nexus 7...

I had this problem and I was unable to get it work until several hours of debugging:

Javascript:
document.getElementById("myDiv").style.marginLeft = "100px";


HTML:
<table><tr><td align=center><div id="myDiv"> . . . </div></td></tr></table>


Guess what? It was due to the very unexpected "align=center" that prevents the div beneath from moving anywhere.

Weird problem. Weird cause.

Read More »

Tuesday, August 6, 2013

Apostrophe (') Gets Censored After Inserting Into MySQL. How to Fix it?

I think MySQL doesn't like apostrophe or '. When inserting into MySQL, the apostrophe goes missing. How to fix this? Simple. Here's it is:

$text = "My car's mirror is broken!";
$text2DB = addslashes($text);
mysql_query("INSERT INTO ... $text2DB ... // complete the MySQL INSERT INTO action here



PHP's addslashes() function is enough to solve this problem. It will add slashes when necessary automatically. Isn't that neat?

Read More »

From Your Check Out Form to Paypal's Note to Seller


If you want to add note to the Paypal seller from your check out form or shopping cart, you need to add the cn input name and value in the post form before submitting to Paypal. Something look like:

<input type=hidden name=cn value="Please ship directly to my dorm room">


If everything is done correctly, the "note to seller" will appear in the Paypal check out form.
Read More »

Auto Login using PHP stream_context_create() and file_get_contents()


The following is just a rough idea of how to log in to a website using PHP. If the target website is owned by you, you should know how it is done. If not, you may need to contact the web administrator before doing so. The web site owner may not like it. The main idea here is to make the login and grab the data out with just one push button to save all the hassels to log in manually. It is advised to make it completely legal before you even try it:

$postdata = http_build_query(
 array(
     'postUserName' => 'yourLoginID',
     'postPassword' => 'yourPassword'
 )
);

$postOptions = array('http' =>
 array(
     'method' => 'POST',
     'header' => 'Cookie: PHPSESSID='.$sessid,
     'content' => $postdata,
     'user_agent'=> $_SERVER['HTTP_USER_AGENT']
 )
);

$context = stream_context_create($postOptions);

$return = file_get_contents("http://yourtargetloginURL.com/targetlogin.php?condition=login", false, $context);
. // check $return if it is compressed. If so, uncompressed it before anything
. // check $return HTML for success/fail login
. // set cookie for successful login
...



For those in green, it depends on your own login environment. Every login situation is different. Some requires certain cookie to be set prior to anything else. Finally, make sure it is legal before you go ahead.

Read More »

My Javascript and PHP Way to Extract the File Extension

Javascript:

var extension;
var filename = "test.my.txt";
var ext = filename.split(".");
if (ext[1] != "") {
     extension = ext[ext.length-1];
}

// extension will contain "txt"


PHP:

$fullfilename = "test.my.txt";
preg_match("/(.+)\.([^\.]+)$/",$fullfilename,$match);
$filename = $match[1];
$extension = $match[2]; // $extension will contain "txt"



I think the codes are very self-explanatory. Enjoy!!!

Read More »

Javascript and PHP Cookie Expiration Setting Technique

Javascript:

var hour = 24; // expire in 24 hours
var tm1 = new Date();
var tm2 = new Date(tm1.getTime()+3600000*hour); // 60*60*1000 = 3600000 ms
var exp = "expires = " + tm2.toUTCString();

document.cookie = 'cookiename = cookievalue;'+exp;


PHP:

$hour = 24;
setcookie("cookiename","cookievalue",time()+(3600*$hour));



For PHP technique, it has a problem. The time() gets the time of the server instead of the browser. In order to get the accurate expiration timing, one needs to either rely on Javascript to set the cookie or obtain the time zone from the browser as I mentioned in my earlier post.

Read More »

My Javascript to Guess Processor's Speed



Updated on 5th of February, 2014: There is an updated version for this posting here.



This is necessary when your web page runs a lots of animation using javascript. If the target browser is slow in computing speed, it is advisable to reduce the amount of animation to run on the machine.

Here's my simple way to check the speed of a computer using simple Javascript:

<script>

var count;
var d = new Date();
var startTime = d.getTime();

for (i=0; i<=1000000; i++) {
count++;
}

var d = new Date();
var endTime = d.getTime();
var myLatency = endTime - startTime;

</script>



myLatency contains my speed index.

After testing using this script, iPad 1 will give myLatency more than 200, iPad 2 between 100 and 200, and iPad 3/4 less than 100.

As for the PC/Mac, myLatency is around 20-100 for dual core processor and quad core processor less than 10. Anyway, the myLatency also depends on the tasks the computer is running in the background concurrently and the core speed in GHz. Anyway, it is just a guess speed Javascript and it should not be treated as a sure thing for the speed test.

Read More »

Monday, August 5, 2013

My Javascript Function to Show UTC Time Zone of Your Browser/Computer


Your computer has its own time zone setting as well as the web host server. Most of the time they are quite different. United States alone has three different time zones.

It is crucial to get the time zone offset off the browser than the server as the time zone is something personal rather than a server sitting on a fixed location that tells nothing about the visitors possibly from the other side of the globe.

Here is a simple Javascript function to get the UTC time zone offset of your browser:

function getBrowserUTCTimezone() {
   x = new Date();
   return x.getTimezoneOffset()/-60;
}



Please note that the offset returned by the Javascript function getTimezoneOffset() will be divided by -60. Why negative? I'm not so sure. The invert of the number seems to give the right offset every time.
Read More »

Sunday, August 4, 2013

JQuery Close-Up: Is it a Good Idea?


JQuery popularity in web development nowadays is similar to Facebook in social network. Developers and programmers love to use it.

The coding is simple and brisk but most people use it just to perform simple tasks on the web pages such as changing the DOM element styles, ie. color, opacity and location.

Many use it to perform tasks that can be easily emulated in conventional Javascript and I think it is over-killing. I now dig a bit digger into JQuery and see if it is worth to have it on your web pages.


Please take a look of the following network performance of a JQuery in a web page. I'm using a slow connection. Pardon me. :)




Do note that the size of jquery-1.9.1.min.js is around 90kB. For slow connections, it is a burden for a web page to loaded with it. But for a fast internet network, the size is acceptable. Please bear in mind that for public internet facilities, the network could be crawling if many of the users are watching video streamed at the same time.

And here's the good news. Browsers nowadays will be able to cache the JQuery library and reuse it when any web pages call for it. Since many web pages (I can almost assume almost all web pages) are using it, the browser most likely won't even need to reload the library when your web pages call for it. Here's the proof of what happened when I reloaded the same web page the 2nd time:




The news gets even better if you load from Google API server. As you can see the library is somewhat "compressed" thus reducing the size to merely 32kB.





My conclusion is that it depends on your reliance on the handy library. If your task to be performed can be easily replaced by simple Javascript, avoid including the library. Who knows somebody might be running your web page the first time without a cache in the browser after having the cache cleared or on a newly installed browser. If the tasks to be performed on a web page are complicated and hard to be replaced by conventional Javascript or the scripts will be too long, go for it!

Read More »

Modifying Your ASP Code to ASPX VB.Net

This could have been a very old topic as ASP (VB) has been phased out long ago and VB.Net is almost obsolete compared with C#. Although VB and VB.net are using the same programming language, the way they work on a web page is vastly different.

Anyway, let's go with the fun of migrating from one programming environment to another.

ASP (VB)

<%
.
.
Dim orange
orange = "apple"
.
.
.
%>

<html>
<body>
.
.
...<%=orange%> . . .
.
.
.
</body>

</html>



ASPX (VB.Net)

<%@ import Namespace="System.IO" %>
<%@ Page Language="vb" Debug="true" %>

<script language="vb" runat="server">

Private orange as String

Sub Page_Load()
.
.
orange = "apple"
.
.
End Sub

</script>

<html>

<body>
.
.
...<% Response.Write(orange) %> . . .
.
.
.
</body>

</html>



It's hard to get used to the new structure of VB.net initially. But once you get it done error-free a few times, you'll get used to it. There are also some syntax changes in VB.net compared to the old VB such as the use of "+" to concatenate strings together instead of using "&".

Anyway, that's all for now and happy coding!!!

Read More »

Sunday, July 21, 2013

Decompress/Unzip Web Content with Content-Encoding: gzip (using PHP - file_get_contents() and gzinflate())


If you are using file_get_contents() to grab content from the web and process using PHP, you may bump into web contents that are compressed using gzencode.

Here's a solution to decompress those content (simplified for easy reference):

<?php

$qdata = array('http' =>
    array(
     'method' => 'POST',
     'user_agent'=> $_SERVER['HTTP_USER_AGENT']
    )
   );

$context = stream_context_create($qdata);

$data = file_get_contents("http://www.urltograbmystuff.com", false, $context);

$u = gzinflate(substr($data,10,-8));
.
.
.


?>


The trick is to use gzinflate() and do remember to change the URL to your target web address. Process your $u (string that contains the HTML codes of the target) afterwards.

Read More »

Compress External Javascript with gzip in PHP


If you are using an external Javascript, you can compress the content before sending it to the browser using PHP.

Here's the solution (simplified for easy reference):

<?php

error_reporting(0); // make sure it is not reporting any warning that will ruin the output

$js = <<<MYJAVASCRIPT
.
.
.
MYJAVASCRIPT;

// Optional: The following three lines of extra codes are to downsize the Javascript further
//$js = preg_replace('|//[^\r^\n]+(\r\n)|','',$js); // Remove Javascript Comment PC version
//$js = preg_replace('|//[^\n]+(\n)|','',$js); // Remove Javascript Comment non-PC version
//$js = preg_replace('/[\r\n\t]/','',$js); // Remove all the newlines and tabs


$compressedJS = gzencode($js,6); // compression ratio = 6

header("Content-type: application/x-javascript");
header("Content-Encoding: gzip");

echo($compressedJS);


?>


You can check the final compressed size easily using Google Chrome Inspect Element (Network) tool:


Before Compression


After Compression

Please ignore the latency as it varies every time I run the page.

If your javascript/HTML/css size is huge, you can use this method to downsize the codes so that visitors from slow internet connection can benefit from this optimization.

Read More »

Saturday, July 20, 2013

Javascript to Dynamically Change the Image Source of an Element for IE


Just like the problem of changing background color for IE via Javascript, changing the image source requires special treatment as well.

Here's the solution (simplified for easy reference):

Javascript:

var ie = (navigator.userAgent.indexOf("MSIE") != -1);

if (!ie) {
   document.getElementById('MyImageID').src = 'myImageSrcName.jpg';
}
else {
   document.getElementById('MyElemID').innerHTML = '<img src="myImageSrcName.jpg">';
}


HTML:

<span id="MyElemID">
<img src="original.jpg" id="MyImageID">
</span>


This is a simple example of how to change an image source from original.jpg to myImageSrcName.jpg dynamically across major browsers.
Read More »

Javascript to Dynamically Change the Background Color of an Element for IE


You can change the background color easily in Chrome, Safari and Firefox.

But for IE, you cannot change it using the easy way like the other browsers are doing it.

Here's the solution (simplified for easy reference):

var ie = (navigator.userAgent.indexOf("MSIE") != -1);

if (!ie) {
   document.getElementById('MyElemID').style.backgroundColor = "#AABBCC";
}
else {
   document.getElementById('MyElemID').style.backgroundColor = "rgb('AA','BB','CC')";
}


Therefore, if you want to accommodate for all browsers, one needs to think of color as RGB components. You either break up the RGB component to suit IE's requirement or combine RGB components into a string to suit the need of Chrome, Safari or Firefox.

Updated on 4th of August 2013:
It is better to use rgb(170,187,204) instead of rgb('AA','BB','CC') stated earlier.



Read More »

Tuesday, June 18, 2013

How to Suppress Default IIS Error and Display PHP Error Instead?


Ever wonder how to make IIS to show the PHP errors instead of its default "semi" blue-screen error page? So that it is easier to debug your PHP codes?

The answer is simple. Just go to your php.ini (mine is in C:\Program Files (x86)\PHP), change display_errors from Off to On. Reboot your PC. (I've tried just restarting the IIS service, it won't use the new PHP setting yet)

Walla! That simple!

If you want to turn off the error/warning altogether, you can always add "error_reporting = 0;" in your PHP script. For example, PHP script to spit out headers, JSON/XML/Binary data.



This following is the screen capture of the php.ini file:


You need to run this editor as Administrator to save this file as php.ini is a system file.

Read More »

Wednesday, March 20, 2013

Protect Your External CSS and Javascript Codes? Possible?


Actually there is no way to protect your Javascript or CSS from being seen.

I've explained a way to sort of protect it from Safari/Firefox/IE in:


http://webtrick101.blogspot.com/2012/08/protect-your-css-and-javascript-codes.html


Nevertheless Chrome can easily show your CSS/Javascript codes to the world.


Since there is no way to block it, you might as well minify your Javascript/CSS codes. In that way, your codes will be harder to be understood and may sway some programmers from getting what they want easily.


Here's a simple way to minify it before you show it to the world using PHP:


Please remove all the comments from your CSS/Javascript codes before using the following minification codes.



For mycss.php:

<?php

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

$css = <<<MYCSS
a {text-decoration:none;color:#777777;}
.
.
.
MYCSS;

echo(preg_replace('/[\r\n\t]/','',$css)); // simple minification

}

?>



For myjs.php:

<?php

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

$js = <<<MYJS
var ie=0;
.
.
.
MYJS;

header("Content-type: application/x-javascript"); // to make sure browser sees it as js
echo(preg_replace('/[\r\n\t]/','',$js)); // simple minification

}


?>


Please note that this is just a simple minification to remove newlines and tabs using PHP's preg_replace. Spaces are not removed due to the 'var ' problem. If the spaces are removed, 'var' will merge with the variable name next to it. This can be solved by several filters to remove other spaces but it is not the purpose of this post to go deep into minification. I better call it "mini minification"! :)

P/S: If you want to retain your comments before sending to the minification process, this can be achieved by removing all the comments using preg_match before the minification.

UPDATE on 1st of April 2013
You can remove the javascript comments by using this preg_replace in PHP:
$js = preg_replace('|//[^\r^\n]+(\r\n)|','',$js);

UPDATE on 17th of April 2013
Sorry if you were using a Unix/Linux based web server, you'll need these to get rid of the comments instead of the codes above:
$js = preg_replace('|//[^\n]+(\n)|','',$js);

To simplify the consistency between both server platforms (MS/Linux), include both filter codes above to remove the comments before minify your javascript.

Read More »

Saturday, March 9, 2013

Weird Javascript setInterval Scenarios in Chrome

This is a weird case.


function dummy() {
.
.
.
}

setInterval(dummy, 1000); // This will WORK in non-Object-Oriented Function
setInterval(dummy(), 1000); // This will not work as it has too many brackets
setInterval("dummy", 1000); // This will not work
setInterval("dummy()", 1000); // This will work even in a Object Oriented Function



I found when I tried to set an interval loop to a OO (Objected Oriented) Function as follows:



function dummy() {
.
.
.
   this.action1 = function() {

      .
      .
      .
   }
.
.
.
}

setInterval(dummy.action1, 1000); // This will NOT work in Object Oriented Function
setInterval(dummy.action1(), 1000); // This will not work as it has too many brackets
setInterval("dummy.action1", 1000); // This will not work
setInterval("dummy.action1()", 1000); // This will work even in a Object Oriented Function



The function without the quotes and bracket will not work. But it works well in a normal non-OO funtion.
This may be something trivial but it is interesting. I haven't tried anything other than Chrome yet. Maybe other browsers are not giving this problem.
Read More »

Wednesday, February 27, 2013

The Curious Case of Missing 'px' in Javascript for Chrome/Safari/Firefox


When one uses the transitional DOCTYPE in Chrome/Safari/Firefox, your Javascript assignment of value to marginTop or top will not be successful if you left out the 'px'.

For example, if you want to move a dummy DIV to a height of 100 pixel from the top, you might do this:


document.getElementById('dummy').style.top = 100;



It will work if you are not using the transitional DOCTYPE. If you are using the transitional DOCTYPE, you need to assign it with a 'px' at the end:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> .
.
.
document.getElementById('dummy').style.top = 100 + 'px';



in order to make it work for Chrome/Safari/Firefox.

As for IE, it will work whether it is in transitional (quirks) mode or not.

Read More »

Friday, February 1, 2013

Javascript to Change Div & Body Style in IFrame

Before showing the codes, here are the conditions that these codes WON'T work:
  • Run with Chrome in localhost environment
  • Cross domain for the main HTML and dummy.html in your iframe. These codes have to comply with the same domain policy or hackers will be very happy if it is not


The Main HTML:


<iframe id="myFrame" scrolling="no" style="overflow: hidden; height: 580px; width: 325px;"
src="dummy.html"></iframe>

<script>

function changeColor() {

    document.getElementById('myFrame').contentWindow.document.getElementById('divInDummy').
style.backgroundColor = '#123456'; // myFrame is the name of your iframe,
divInDummy is the DIV name in the iframe


    document.getElementById('myFrame').contentWindow.document.body.style.backgroundColor = "#234567";
// change the body color of iframe

}

changeColor();

</script>




The dummy.html:



<html>

<body bgcolor="#ccaaee">

Hello World! My name is dummy.html
<div id=divInDummy style="background:#55aadd;width:120px;height:120px">
<table><tr><td><br> <br><br>I am inside a DIV<br><br>
</td></tr></table>
</div>

</body>

</html>



If you think the dummy.html is not able to load before you call the script, you can put it in an interval loop to make sure the function is called successfully eventually. Here's the code: setInterval('changeColor()', 1000);

Read More »

Thursday, January 31, 2013

Facebook Fan/Like Box External CSS No Longer Supported?





Updated: 8th of September 2013
After several months of waiting, FB no longer supports external CSS as of today. Here's my alternative to change the border color of the like box:
http://webtrick101.blogspot.com/2013/09/latest-method-to-change-facebook-like.html





Updated: 27th of February 2013
As of yesterday, this method is no longer working. Let's wait for a few more days and see if Facebook turns this feature back on.



Updated: 1st of March 2013 (Not Working Anymore)
If you use http://www.facebook.com/plugins/likebox.php instead of http://www.connect.facebook.com/widgets/fan.php as your like box script, you can still control the color of the iframe by adding the border style to it. As of now, the external CSS is still not supported.





Actually it is still supported but the method used has changed.

Here's the latest format/method:


<iframe style="height: 400px; width: 310px; border: 0" src="http://www.connect.facebook.com/widgets/fan.php?href=[FAN PAGE URL]&colorscheme=light&show_faces=true&stream=true&header=false&css=[CSS URL]"></iframe>


Instead of using <fb:fan> tag, iframe is used. As for the [FAN PAGE URL], you can put something like http%3A%2F%2Fwww.facebook.com%2FmyFBpage. Please note that %3A means ':', %2F means '/'. The same goes for the CSS URL. Just point to a css file.

Enjoy!
Read More »

Wednesday, January 2, 2013

Happy 2013! The Winners and Losers of Browsers

My first post in 2013! Web developers' number one concern is always the browser popularity. We simply cannot afford to develop a web page that only runs well on a browser that is seldom used by the public.

Here's the latest stat from WikiMedia as of October 2012 for non-mobile browser:



The winner is Google for 2012!!!

As for the mobile version, my guess is either Google or Apple. I think they are in stiff competition something like 50/50. But for America, I think Apple Safari won the competition where iPad and iPhone are very popular. As for the rest of the world, Google has the edge.

Let see how this competition turns out later part of 2013.

Have a enjoyable 2013! Happy coding!

Read More »