Wednesday, December 31, 2014

Simple Javascript to Move and Fade Element without JQuery

This is just a combination of my previous post on moving and fading elements without JQuery. I just combine the two functions so that I can move elements and at the same time fade them. Here are the links to my previous posts:

1. Simple Javascript Fade In/Out Function without JQuery
2. Simple Javascript Element Moving Function without JQuery

The combination of these two functions:

<html>
<script>

var moveSpeed = 100; // interval in ms, smaller means faster
var moveStep = 10; // pixel count in every move, bigger means faster

function moveObj(elemID) {

 this.id = elemID;
 this.x = -1;
 this.y = -1;
 this.targetX;
 this.targetY;
 this.timerX;
 this.timerY;
 this.directionX;
 this.directionY;

 this.moveHorizontal = function(x1,x2) {
  clearInterval(this.timerX); // cancel earlier movement if any
  x2<x1? this.directionX = 'left':this.directionX = 'right';
  this.x = x1;
  document.getElementById(this.id).style.left = x1+'px';
  this.targetX = x2;
  var tempObj = this;
  this.timerX = setInterval(function() { move(tempObj,'hor'); },moveSpeed);
 };

 this.moveVertical = function(y1,y2) {
  clearInterval(this.timerY); // cancel earlier movement if any
  y2<y1? this.directionY = 'up':this.directionY = 'down';
  this.y = y1;
  document.getElementById(this.id).style.top = y1+'px';
  this.targetY = y2;
  var tempObj = this;
  this.timerY = setInterval(function() { move(tempObj,'ver'); },moveSpeed);
 };
}

function move(obj,movement) {

 if (movement == 'hor') {
  obj.directionX == 'left'? obj.x-=moveStep:obj.x+=moveStep; //You can change it to non-linear movement here by applying formula instead just adding/subtracting in a linear fashion
  if ((obj.directionX == 'left' && obj.x < obj.targetX) || (obj.directionX == 'right' && obj.x > obj.targetX)) {
   clearInterval(obj.timerX);
  }
  else {
   document.getElementById(obj.id).style.left = obj.x + 'px';
  }
 }
 else {
  obj.directionY == 'up'? obj.y-=moveStep:obj.y+=moveStep; //You can change it to non-linear movement here as above
  if ((obj.directionY == 'up' && obj.y < obj.targetY) || (obj.directionY == 'down' && obj.y > obj.targetY)) {
   clearInterval(obj.timerY);
  }
  else {
   document.getElementById(obj.id).style.top = obj.y + 'px';
  }
 }

}


var fadeSpeed = 100;

function fadeObj(elemName) {

 this.name = elemName;
 this.opacity = -1; // -1 indicates a new obj
 this.timer;

 this.fadeOut = function(delay) {
  if (this.opacity == -1) {
   setOpacity(this.name,10);
   this.opacity = 10;
  }
  var tempObj = this;
  setTimeout(function(){tempObj.timer = setInterval(function() { fade(tempObj,'out'); },fadeSpeed)},delay);
 };

 this.fadeIn = function(delay) {
  if (this.opacity == -1) {
   setOpacity(this.name,0);
   this.opacity = 0;
  }
  var tempObj = this;
  setTimeout(function(){tempObj.timer = setInterval(function() { fade(tempObj,'in'); },fadeSpeed)},delay);
 };

}

function fade(obj,direction) {

 if (direction == 'out') {
  obj.opacity--;
  if (obj.opacity >= 0) {
   setOpacity(obj.name,obj.opacity);
  }
  else {
   clearInterval(obj.timer);
  }
 }
 else {
  obj.opacity++;
  if (obj.opacity <= 10) {
   setOpacity(obj.name,obj.opacity);
  }
  else {
   clearInterval(obj.timer);
  }
 }

}

function setOpacity(elemName,value) { // opacity from 0 to 10

 document.getElementById(elemName).style.MozOpacity = value/10;
 document.getElementById(elemName).style.opacity = value/10;
 document.getElementById(elemName).style.filter = 'alpha(opacity=' + value*10 + ')';

}

</script>

<body>
<span id="animateMe" style="position:absolute;top:100px">Hello</span>
<br>

<script>

var moveElem = new moveObj('animateMe');
var fadeElem = new fadeObj('animateMe');
moveElem.moveHorizontal(200,100);
moveElem.moveVertical(100,260);
fadeElem.fadeOut();
setTimeout(function() {moveElem.moveHorizontal(100,500);},2000); // run this movement 2000ms later
setTimeout(function() {moveElem.moveVertical(260,100);},2000); // run this movement 2000ms later
fadeElem.fadeIn(2000); // run this movement 2000ms later

</script>

</body>
</html>


Here they are! You can also add more functions to this animation Javascript library such as the resizing element function. The easiest way is to use JQuery. But this post is not about replacing JQuery. It's about showing those who are curious about how animation can be done without JQuery in simple Javascript functions.

Read More »

Tuesday, December 30, 2014

Javascript to Zoom According to a Maximum Browser's Width


There will be times when you need to perform some zooming on the browser so that you'll see what things will look like in other resolutions. For example, if you need to know how your website looks like on an iPhone screen, you might this Javascript function that I am going to show you. But make sure you know the target screen resolution before you try the following codes out:

<html>
<script>

var width,zoomPercentage;

function setWidth(pixel) {

 if (!pixel) {
  zoomPercentage = 100;
 }
 else {
  if (navigator.userAgent.indexOf("MSIE") != -1) { // IE
   width = document.documentElement.offsetWidth;
  }
  else {
   width = document.getElementsByTagName("body")[0].clientWidth;
  }
  zoomPercentage = Math.round((width/pixel)*100);
 }

 document.body.style.zoom = zoomPercentage+"%";
}

</script>

<body>

Hello World!<br>

<a href="javascript:setWidth(800)">800 pixel</a> <a href="javascript:setWidth(1024)">1024 pixel</a> <a href="javascript:setWidth(1280)">1280 pixel</a> <a href="javascript:setWidth(1920)">1920 pixel</a> <a href="javascript:setWidth(0)">default pixel</a>

<br><img src="http://www.freeimageslive.com/galleries/backdrops/colourful/pics/background01331.jpg">

</body>
</html>



You can replace your HTML codes to replace the image I inserted to see the zoom effect clearly. Please note that the most important part of the codes is in green text. Please also note that these codes may not run well in all IE versions. It is recommended to use a non-IE browser to try it out.
Read More »

Wednesday, December 24, 2014

Simple Javascript Element Moving Function without JQuery


This is similar with my previous post except this is for moving HTML elements instead of fading them.



Note: Again, this is not to replace the existing JQuery codes. This is just for those who are curious about how things are moved with only Javascript codes without JQuery.

Here are the codes:

<html>
<script>

var moveSpeed = 100; // interval in ms, smaller means faster
var moveStep = 10; // pixel count in every move, bigger means faster

function moveObj(elemID) {

 this.id = elemID;
 this.x = -1;
 this.y = -1;
 this.targetX;
 this.targetY;
 this.timerX;
 this.timerY;
 this.directionX;
 this.directionY;

 this.moveHorizontal = function(x1,x2,delay) {
  clearInterval(this.timerX); // cancel earlier movement if any
  x2<x1? this.directionX = 'left':this.directionX = 'right';
  this.x = x1;
  document.getElementById(this.id).style.left = x1+'px';
  this.targetX = x2;
  var tempObj = this;
  this.timerX = setInterval(function() { move(tempObj,'hor'); },moveSpeed);
 };

 this.moveVertical = function(y1,y2,delay) {
  clearInterval(this.timerY); // cancel earlier movement if any
  y2<y1? this.directionY = 'up':this.directionY = 'down';
  this.y = y1;
  document.getElementById(this.id).style.top = y1+'px';
  this.targetY = y2;
  var tempObj = this;
  this.timerY = setInterval(function() { move(tempObj,'ver'); },moveSpeed);
 };
}

function move(obj,movement) {

 if (movement == 'hor') {
  obj.directionX == 'left'? obj.x-=moveStep:obj.x+=moveStep; //You can change it to non-linear movement here by applying formula instead just adding/subtracting in a linear fashion
  if ((obj.directionX == 'left' && obj.x < obj.targetX) || (obj.directionX == 'right' && obj.x > obj.targetX)) {
   clearInterval(obj.timerX);
  }
  else {
   document.getElementById(obj.id).style.left = obj.x + 'px';
  }
 }
 else {
  obj.directionY == 'up'? obj.y-=moveStep:obj.y+=moveStep; //You can change it to non-linear movement here as above
  if ((obj.directionY == 'up' && obj.y < obj.targetY) || (obj.directionY == 'down' && obj.y > obj.targetY)) {
   clearInterval(obj.timerY);
  }
  else {
   document.getElementById(obj.id).style.top = obj.y + 'px';
  }
 }

}

</script>

<body>
<span id="moveMe" style="position:absolute;top:100px">Hello</span>
<br>

<script>
var helloElem = new moveObj('moveMe');
helloElem.moveHorizontal(200,100,0);
helloElem.moveVertical(100,260,0);
setTimeout(function() {helloElem.moveHorizontal(100,500);},2000); // run this movement 2000ms later
setTimeout(function() {helloElem.moveVertical(260,100);},6000); // run this movement 6000ms later
setTimeout(function() {helloElem.moveHorizontal(500,100);},6000); // run this movement 6000ms later

</script>

</body>
</html>


You can try it out and see if it works almost like JQuery. With these codes, you have more control over the speed. You can change it to non-linear movement like JQuery with adding/subtracting pixel movement with a non-linear formula.

I have also combined the moving and fading function together to make it more interesting:

http://webtrick101.blogspot.com/2014/12/simple-javascript-to-move-and-fade.html

Read More »

Thursday, December 18, 2014

Latest Facebook Share Method for HTML (Dec 2014)

The Facebook share method has gone through a lots of changes since my last post long ago. Here is the latest update. Please note that these codes may not be working by the time you use them as Facebook updates its coding requirements very often.

Anyway, here are the codes:

<html>
<head>
<meta name="description" content="Welcome to my website! My phone number is 1234567! Thank you!">
<meta property="og:title" content="Your Facebook Post Title" />
<meta property="og:type" content="website" />
<meta property="og:image" content="http://yourdomainname.com/pic1.jpg" />
<meta property="og:url" content="http://yourdomainname.com" />
</head>
<body>

<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>

<div id="share">
<fb:share-button class="meta">
<link rel="image_src" href="http://yourdomainname.com" />
<link rel="target_url" href="http://yourdomainname.com" />
</fb:share-button>
</div>

</body>
</html>


Note: Please note that you need to own the website in order to place these codes in the index page. If you don't own the website or domain, the share information will not show up correctly. Secondly, if you run these codes on the "localhost", the share button won't show up. Please note that you need to change those in blue to your own information.

If the information doesn't show up correctly or you want to update your Facebook share information, you need to use Facebook linter or debugger. Here's the link: https://developers.facebook.com/tools/debug/. The linter/debugger link has also changed since my last post. Please also note that you may need to press "Fetch new scrape information" a few times for the system to update.

Read More »

Wednesday, December 10, 2014

Simple Javascript Fade In/Out Function without JQuery


If you want to know how to write your own animation function such as those in JQuery, here is one of them. Please note that this is not to replace your JQuery scripts, it is just for those who are curious about how it can be done without JQuery.

Note: I also have similar codes for movement/animation here. You can combine these two capabilities to make it fade while moving. Of course, that can be a bit challenging.

Here are the codes:

<html>
<script>

var fadeSpeed = 100;

function fadeObj(elemName) {

 this.name = elemName;
 this.opacity = -1; // -1 indicates a new obj
 this.timer;

 this.fadeOut = function(delay) {
  if (this.opacity == -1) {
   setOpacity(this.name,10);
   this.opacity = 10;
  }
  var tempObj = this;
  setTimeout(function(){tempObj.timer = setInterval(function() { fade(tempObj,'out'); },fadeSpeed)},delay);
 };

 this.fadeIn = function(delay) {
  if (this.opacity == -1) {
   setOpacity(this.name,0);
   this.opacity = 0;
  }
  var tempObj = this;
  setTimeout(function(){tempObj.timer = setInterval(function() { fade(tempObj,'in'); },fadeSpeed)},delay);
 };

}

function fade(obj,direction) {

 if (direction == 'out') {
  obj.opacity--;
  if (obj.opacity >= 0) {
   setOpacity(obj.name,obj.opacity);
  }
  else {
   clearInterval(obj.timer);
  }
 }
 else {
  obj.opacity++;
  if (obj.opacity <= 10) {
   setOpacity(obj.name,obj.opacity);
  }
  else {
   clearInterval(obj.timer);
  }
 }

}

function setOpacity(elemName,value) { // opacity from 0 to 10

 document.getElementById(elemName).style.MozOpacity = value/10;
 document.getElementById(elemName).style.opacity = value/10;
 document.getElementById(elemName).style.filter = 'alpha(opacity=' + value*10 + ')';

}

</script>

<body>
<span id="fadeMe" style="height:100px">Hello</span>

<script>
var helloObj = new fadeObj('fadeMe');
helloObj.fadeOut();
helloObj.fadeIn(2000); // fade in 2000ms later
</script>

</body>
</html>


The 'Hello' text will first fade out and fade back in. I create an object to handle the element by keep tracking of its opacity, element name and timer. Then I sent to a timer to do the fading process. You can also add some other function to it such as fading non-stop, fade from one opacity value to another, avoid double fading events on the same element. I just show you the most basic form of the fading function. You can add a lot more fun to it.

You can also do something cool like this using my codes above:

<body>


<span id="fadeMe1" style="height:100px">H</span><span id="fadeMe2" style="height:100px">e</span><span id="fadeMe3" style="height:100px">l</span><span id="fadeMe4" style="height:100px">l</span><span id="fadeMe5" style="height:100px">o</span>

<script>

var helloElem1 = new fadeObj('fadeMe1');
var helloElem2 = new fadeObj('fadeMe2');
var helloElem3 = new fadeObj('fadeMe3');
var helloElem4 = new fadeObj('fadeMe4');
var helloElem5 = new fadeObj('fadeMe5');

helloElem1.fadeOut(0);
helloElem2.fadeOut(100);
helloElem3.fadeOut(200);
helloElem4.fadeOut(300);
helloElem5.fadeOut(400);
helloElem1.fadeIn(2200);
helloElem2.fadeIn(2400);
helloElem3.fadeIn(2600);
helloElem4.fadeIn(2800);
helloElem5.fadeIn(3000);

</script>




Replace those codes in the body tag with those above. Enjoy!

P.S.: For this to work on IE, you need to specify the width or height for the <span> you are working with.

Read More »

Monday, November 17, 2014

Javascript Color Morphing


Here is a little fun thing to do in the lab: changing colors. If you have a little javascript project and you want to make it fun, this little color morphing script can come in handy. It opens up the door to understanding how the color components on your screen works. The combination of red, green and blue to make up a color you see on a screen can be shown in this little experiment. Here are the codes:

<html>
<head>
<script>

var runTimer;
var rCom, gCom, bCom; // Red, Green, Blue component
var rComN, gComN, bComN; // Red, Green, Blue step/speed
var rComDir, gComDir, bComDir; // Red, Green, Blue direction (value going up/down)
var tRCom, tGCom, tBCom; // target Red, Green, Blue component
var morphSpeed = 100; // 100ms interval between changes
var started = 0;
var currentRGB;

function runColorBar() {

 if (!started) {
  rCom = Math.floor((Math.random()*256)).toString(16); // random color start for red component
  gCom = Math.floor((Math.random()*256)).toString(16); // you can also fix it to something like "AA" in hex or 170 in decimal
  bCom = Math.floor((Math.random()*256)).toString(16);
  rComDir = Math.floor((Math.random()*1))+1; // random direction - increasing or decreasing
  gComDir = Math.floor((Math.random()*1))+1;
  bComDir = Math.floor((Math.random()*1))+1;
  rComN = Math.floor((Math.random()*5))+1; // random increasing/decreasing speed
  gComN = Math.floor((Math.random()*5))+1;
  bComN = Math.floor((Math.random()*5))+1;
  runTimer = setInterval("changeBarColor()",morphSpeed);
  started = 1;
 }

}

function stopColorBar() {

 if (started) {
  clearInterval(runTimer);
  started = 0;
 }

}


function changeBarColor() {

 tRCom = parseInt(rCom, 16);
 rComDir == 1?tRCom+=rComN:tRCom-=rComN; // decide to increase or decrease color value

 tGCom = parseInt(gCom, 16);
 gComDir == 1?tGCom+=gComN:tGCom-=gComN;

 tBCom = parseInt(bCom, 16);
 bComDir == 1?tBCom+=bComN:tBCom-=bComN;

 if (tRCom >= 255) { // if overshoot, change direction
  rComDir = 2;
  tRCom = 255;
 }
 else if (tRCom <= 0) {
  rComDir = 1;
  tRCom = 0;
 }
 if (tGCom >= 255) {
  gComDir = 2;
  tGCom = 255;
 }
 else if (tGCom <= 0) {
  gComDir = 1;
  tGCom = 0;
 }
 if (tBCom >= 255) {
  bComDir = 2;
  tBCom = 255;
 }
 else if (tBCom <= 0) {
  bComDir = 1;
  tBCom = 0;
 }

 rCom = tRCom.toString(16);
 gCom = tGCom.toString(16);
 bCom = tBCom.toString(16);

 if (rCom.length == 1) { rCom = "0"+rCom; } // every color component requires at least two digits
 if (gCom.length == 1) { gCom = "0"+gCom; }
 if (bCom.length == 1) { bCom = "0"+bCom; }

 currentRGB = "#"+rCom+gCom+bCom;
 document.getElementById('colorBar').style.backgroundColor = currentRGB;
 document.getElementById('cvalue').innerHTML = currentRGB;

}

</script>

<body onload="runColorBar()"> <table width=500 align=center valign=top><tr><td width=500 height=20 align=center id=colorBar>Color Bar</td></tr><tr><td align=center><br><a href="javascript:stopColorBar()">Stop Morphing</a> <a href="javascript:runColorBar()">Run Color Bar</a><br><br>Current Color Value: <span id=cvalue></span></td></table>

</body>
</html>


Of course, if you understand all the mechanics in the codes, you can reset the values to something of your preference such as the color at the beginning, the speed of color morphing for each color component and so forth. I hope you enjoy this little experiment in this Javascript lab and I'll see you in the coming experiments!

Read More »

Tuesday, November 11, 2014

Auto Copyright Year Javascript

In order to avoid visitors to see outdated copyright information or having someone to help out updating the copyright year on every new year, a simple Javascript can do the job easily. Here is an example of how it is done in a simple web page with a dummy copyright text:


<html>
<body>

© copyright 2007-<span id=currentYear>2013</span>. All rights reserved.

<script>
 var thisYear = new Date().getFullYear();
 document.getElementById('currentYear').innerHTML = thisYear;
</script>

</body>
</html>


Note: Make sure the Javascript is placed after the SPAN tag or you'll get an error for not being to find the 'currentYear' element.

Now you can sit back and relax during new year every year!

Read More »

Monday, November 10, 2014

Create Dynamic Google Map using Javascript

Why do we need to use Javascript to generate Google map dynamically? The answer is speed. If we tell our browser to load everything at the same time, everything will be loaded slower compared to letting browser to complete the important ones before the non-critical one such as the Google map.

I've done some testing and it shows that Google is slowing down the loading of other items on a web page. I compare the loading time of a web page with and without Google map. The one with concurrent Google map loading is showing up images much slower than the one without.

So I've decided to use Javascript to load the Google map dynamically only after all the images are loaded on a web page.

Here are the example for the Google map to be loaded only after the web page body is loaded:


<html>
<head>
<style>
#map_canvas {
width: 500px;
height: 400px;
}
</style>
</head>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
 var myLatlng = new google.maps.LatLng(40.689452, -74.044521);
 var map_canvas = document.getElementById('map_canvas');
 var map_options = {
  center: new google.maps.LatLng(40.689452, -74.044521),
  zoom: 11,
  width: 500,
  height: 400,
  mapTypeId: google.maps.MapTypeId.ROADMAP
 }
  var map = new google.maps.Map(map_canvas, map_options);
 var marker = new google.maps.Marker({
  position: myLatlng,   map: map,
  title: 'Statue of Liberty'
 });
 google.maps.event.addDomListener(map_canvas, 'load', initialize);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>


Of course, you need to place the initialize() function to the location that you think it is the best time to load the Google map. For this case, I choose to place it in the onload listener in the BODY tag. You can change the size and zoom level according to your need.

If you want to load only after certain image is loaded, you can check out my tutorial on how to use Javascript to check whether an image is loaded here.

Read More »

Tuesday, October 28, 2014

onload Priority for Chrome, Safari, Firefox and Internet Explorer

I always wonder how the location of the placement of onload event listener will affect the behavior of my Javascript on various browsers. I use the following codes to check out this small doubt of me:


<html>
<head>
<script>
window.onload = function() {
 alert("window.onload in the head");
}
</script>
</head>

<body onload="alert('body begins onload')">
<br><br><br><br><br><br>
<script>
 alert("body ends onload");
</script>
</body>
</html>


The following are the results of the test on various browser according to the priority of the alert message:
Chrome: "body ends onload", "window.onload in the head", "body begins onload"
Safari/Firefox/IE: "body ends onload", "body begins onload"

I then add an extra onload listener in the body to see if it changes the result. The codes are as follows:


<html>
<head>
<script>
window.onload = function() {
 alert("window.onload in the head");
}
</script>
</head>

<body onload="alert('body begins onload')">
<script>
window.onload = function() {
 alert("window.onload in the body");
}
</script>
<br><br><br><br><br><br> <script>
 alert("body ends onload");
</script>
</body>
</html>


The following are the results of the test on various browser for this new tweak:
Chrome: "body ends onload", "body begins onload", "window.onload in the body"
Safari/Firefox/IE: "body ends onload", "window.onload in the body"


CONCLUSION:
The Chrome browser behave slightly different from the pack. If the window.onload listener is in the head, it will have higher precedence over the onload in the body tag. If the window.onload is in the body, it will have less priority than the one in the body tag with the one in the head ignored.

As for the other browsers, the window.onload in the body will replace the one in the body tag.

One needs to pay special attention to Chrome as it will take all the onload listener in HTML seriously and the programmer needs to make sure the onload script is not running the same script twice or more.

Read More »

Monday, October 13, 2014

Javascript to Simulate Shaking an Object

I know this is trivial but also fun at the same time. Just in case you need something fun for your school projects. You need to modify it to suit your need as the codes in the following is very minimal:


<html>
<script>

var x = 10;
var y = 10;
var myTimer;

function startshake() {
 setTimeout(function() {moveElemX("shakeObject",x-(Math.floor(Math.random()*6)));},10);
 setTimeout(function() {moveElemX("shakeObject",x+(Math.floor(Math.random()*7)));},25);
 setTimeout(function() {moveElemX("shakeObject",x-(Math.floor(Math.random()*5)));},40);
 setTimeout(function() {moveElemX("shakeObject",x+(Math.floor(Math.random()*6)));},55);
 setTimeout(function() {moveElemX("shakeObject",x-(Math.floor(Math.random()*8)));},70);
 setTimeout(function() {moveElemX("shakeObject",x);},85);
 setTimeout(function() {moveElemY("shakeObject",y-(Math.floor(Math.random()*7)));},15);
 setTimeout(function() {moveElemY("shakeObject",y+(Math.floor(Math.random()*3)));},35);
 setTimeout(function() {moveElemY("shakeObject",y-(Math.floor(Math.random()*5)));},45);
 setTimeout(function() {moveElemY("shakeObject",y+(Math.floor(Math.random()*7)));},65);
 setTimeout(function() {moveElemY("shakeObject",y-(Math.floor(Math.random()*5)));},80);
 setTimeout(function() {moveElemY("shakeObject",y);},95);
}


function stopshake() {
 clearInterval(myTimer);
 document.getElementById(elemName).style.top = y+"px";
 document.getElementById(elemName).style.left = x+"px";
}

function moveElemX(elemName,X) {
 document.getElementById(elemName).style.left = X+"px";
}

function moveElemY(elemName,Y) {
 document.getElementById(elemName).style.top = Y+"px";
}


</script>
<body>

<span id="shakeObject" style="position:absolute;top:10px;left:10px">
<table bgcolor="#ffff22" cellpadding=2 cellspacing=2 align=center valign=middle><tr><td>Telephone</td></tr></table>
</span>

<script>
myTimer = setInterval("startshake()",1000);
</script>

<br><br><br>
<a href="javascript:stopshake()">Stop Shaking</a>
</body>

</html>


This is just an example. There are still many other ways to do it. You can also change the timer or offset to other values that suit your need. Hope you like it!

Read More »

Monday, October 6, 2014

Fixed DIV for Browsers (Including IE and Tablets) using CSS

Without using Javascript, CSS is enough to do the job:


<!DOCTYPE HTML>
<html>

<style type="text/css">
#fixit { position: absolute; left: 10px; top: 10px; }
div > div#fixit { position: fixed; }

</style>

<body>

<div>
<div id="fixit" style="border:2px solid #333;background-color:#ddd;text-align:center;padding:10px;"> Hello </div>
</div>

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
</html>


Try scrolling the page. The "Hello" tag won't move. Please pay attention to those in green. Especially the DOCTYPE declaration.
Read More »

Sunday, August 31, 2014

Turn PHP Output Buffer Off to Make it Live on IIS


Questions will be raised on why we need such a trivial feature on our machines? The answer is simple, we want to turn our browser into a server console. When we deal with a extremely large database and we use PHP to process it, we really need the live update on the browser to see the progress as it may take a few hours to complete. Especially when it comes to debugging the PHP during the MySQL processing, any problem will be immediately spotted if it is being run live. If not, you may only realize there is a bug in your program hours later. Then you need to wait for a few more hours to find out more about the outcome again. Live update of browsers will come in handy for cases like I mentioned.

The method:

Change two things in php.ini in c:\Program Files (x86) folder.

1. output_buffering = Off
2. max_execution_time = 0

NOW REMEMBER TO REBOOT YOUR PC!





There are a lots of recommendations on the web such as changing certain values in IIS (PHP-CGI) and using flush() or ob_flush() in PHP. I've tried them. They don't work.

However, the following codes need to be used to clear the buffer before the PHP can become live:


<?php

ob_implicit_flush();
header("Content-Type: text/html");

for ($i=0; $i < 4150; $i++) {
  echo ' ';
}

// The following is not needed as it is just to make sure your PHP can go live.

for($i=0; $i < 5; $i++){
  echo $i . '<br>';
  sleep(1);
}

?>



Why 4150? I've done some testings on two machines and it seems that the number has to be more than 4096 (default buffer size). 4150 seems to be OK on both machines although one machine can go as low as 4130.



If you running PHP on IIS, you'll need to set your IIS to allow the execution of PHP to run longer. Here are the steps to set the IIS (Windows 7):


Start->My Computer (Right Click)


IIS->FastCGI Settings


Double Click on the FastCGI exe file or right click -> Edit.




Set the Activity and Request Timeout value to higher number (in seceonds).

Restart your PC.

Read More »

Tuesday, August 19, 2014

Drawing Line Using Javascript (with Anti-alias Smoothening)


Caveat: It will not look good if the line is steep. Extra work is required to fix this script to render good steep lines.

This is my in-house recipe for anti-alias smoothening of line drawing using Javascript. It is not perfect and it is mainly for educational purposes. It might not be suitable for commercial web sites. If you don't want the anti-alias feature, you can try my plain line drawing Javascript.

Here we go:


<html>

<script>

var spanTag,spanTag1,spanTag2;
var red,red1,red2;
var green,green1,green2;
var blue,blue1,blue2;
var colorChannel;

function mkDotAS(x,y,color,aliasingFactor) {

  colorChannel = color.match(/\#(\w\w)(\w\w)(\w\w)/);

  red = parseInt(colorChannel[1],16);
  green = parseInt(colorChannel[2],16);
  blue = parseInt(colorChannel[3],16);

  red1 = red + parseInt((255-red) * aliasingFactor);
  green1 = green + parseInt((255-green) * aliasingFactor);
  blue1 = blue + parseInt((255-blue) * aliasingFactor);
  red1 = red1>255?255:red1; green1 = green1>255?255:green1; blue1 = blue1>255?255:blue1;

  red2 = red + parseInt((255-red) * (1-aliasingFactor));
  green2 = green + parseInt((255-green) * (1-aliasingFactor));
  blue2 = blue + parseInt((255-blue) * (1-aliasingFactor));
  red2 = red2>255?255:red2; green2 = green2>255?255:green2; blue2 = blue2>255?255:blue2;

  spanTag = document.createElement("span");
  spanTag.innerHTML = '<img src="dummy1x1.png" height=1 width=1>';
  spanTag.style.position = "absolute";
  spanTag.style.zIndex = 1;
  spanTag.style.left = x + "px";
  spanTag.style.top = y + "px";

  spanTag1 = document.createElement("span");
  spanTag1.innerHTML = '<img src="dummy1x1.png" height=1 width=1>';
  spanTag1.style.position = "absolute";
  spanTag1.style.zIndex = 1;
  spanTag1.style.left = x + "px";
  y--;
  spanTag1.style.top = y + "px";

  spanTag2 = document.createElement("span");
  spanTag2.innerHTML = '<img src="dummy1x1.png" height=1 width=1>';
  spanTag2.style.position = "absolute";
  spanTag2.style.zIndex = 1;
  spanTag2.style.left = x + "px";
  y+=2;
  spanTag2.style.top = y + "px";

  red = red>=16?red.toString(16):"0"+red.toString(16);
  green = green>=16?green.toString(16):"0"+green.toString(16);
  blue = blue>=16?blue.toString(16):"0"+blue.toString(16);

  red1 = red1>=16?red1.toString(16):"0"+red1.toString(16);
  green1 = green1>=16?green1.toString(16):"0"+green1.toString(16);
  blue1 = blue1>=16?blue1.toString(16):"0"+blue1.toString(16);

  red2 = red2>=16?red2.toString(16):"0"+red2.toString(16);
  green2 = green2>=16?green2.toString(16):"0"+green2.toString(16);
  blue2 = blue2>=16?blue2.toString(16):"0"+blue2.toString(16);

  spanTag.style.backgroundColor = "#"+red+green+blue;
  spanTag1.style.backgroundColor = "#"+red1+green1+blue1;
  spanTag2.style.backgroundColor = "#"+red2+green2+blue2;

  document.body.appendChild(spanTag);
  document.body.appendChild(spanTag1);
  document.body.appendChild(spanTag2);
}

function drawLineAS(x1,y1,x2,y2,color) {

  var i,j,x,y,m,d,done=0;
  var intMx,floatMx,diff=0;
  x=Math.abs(x1);
  y=Math.abs(y1);
  m=(y2-y1)/(x2-x1);
  d=x1>x2?"-":"+";
  c=y1-(m*x);
 
  while (!done) {
   mkDotAS(x,y,color,diff);
   if (x==x2) { done = 1; }
   if (d=="-") { x--; }
   else { x++; }

   y = parseInt(m*x) + c;
   floatMx = m*x; intMx = parseInt(m*x); diff = floatMx-intMx;
  }
}

window.onload = function() { // only can call after the body is loaded
  drawLineAS(10,40,1000,320,"#3388cc");
};

</script>

<body>
...
</body>

</html>


Actually, this is quite similar to my non-anti-alias version. You can refer to my earlier post on the basic of line drawing using Javascript. To make the story short, a picture worths a thousand words:



Beside the original non-anti-alias line, I just add the spanTag1 and spanTag2 which respectively being placed 1 pixel above and below the original non-anti-alias line. spanTag1 and spanTag2 are the lighter version of the original pixel. The brightness depends on the difference between the floating number of m*x and the integer number of m*x. Since our screen cannot take floating number, the integer number or rounded number offers an inaccurate representation of the actual line. The difference (between floating and integer of m*x) is then being used to calculate the intensity of the lighter version of original pixel color. The one above and the below are being made to be complementing each other to make up a complete bright pixel. This means that if the one above is 25% brighter, the one below will be 75% brighter and vice versa. It is a bit hard to explain, but here it is. I hope this post is clear enough for those who want to know the basic of anti-aliasing for line drawing. Enjoy!

P.S.: In order for the above example to work, you need to place the dummy1x1.png in the same folder you running the HTML. You can get the dummy transparent 1x1 pixel image here if you don't image editing software to help you.

Read More »

Drawing Line Using Javascript


Updated on 27th of August: Please use the 2nd version of my drawLine() function (scroll to the bottom of this page) if possible. The first version has a lots of flaws which may not draw the line correctly in certain situation.



With HTML5 coming hot and jQuery to be well received by web developers, Javascript is now a frozen cake from the fridge. Especially when it comes to drawing shapes on browsers, Javascript will be receiving less and less focus especially when HTML5 flocks into web applications someday.

Although Javascript is becoming less and less important, I still post my way of drawing lines on browsers using Javascript due to the fact that Javascript is still a good educational language for beginners to start with. The readability of jQuery is too low and may turn some newcomers away. That is why I still insist on posting Javascript goodies here. Hope this last piece of cake does not end up in the dumpster.

Note: The anti-alias version can be found here.

Here we go (the codes):


<html>

<script>

var spanTag,red,green,blue; // declare these as global
var colorChannel; // to save resources

function mkDot(x,y,color) {

  colorChannel = color.match(/\#(\w\w)(\w\w)(\w\w)/); // match out RGB
  red = parseInt(colorChannel[1],16);
  green = parseInt(colorChannel[2],16);
  blue = parseInt(colorChannel[3],16);

  spanTag = document.createElement("span");
  spanTag.innerHTML = '<img src="dummy1x1.png" height=1 width=1>';// You need a 1x1 dummy transparent PNG image as foreground
  spanTag.style.position = "absolute";
  spanTag.style.zIndex = 1; // In case you have other elements on the same page
  spanTag.style.left = x + "px";
  spanTag.style.top = y + "px";

  red = red>=16?red.toString(16):"0"+red.toString(16); // convert to HEX
  green = green>=16?green.toString(16):"0"+green.toString(16);
  blue = blue>=16?blue.toString(16):"0"+blue.toString(16);
  spanTag.style.backgroundColor = "#"+red+green+blue; // set background color

  document.body.appendChild(spanTag);
}

function drawLine(x1,y1,x2,y2,color) {
  var i,j,x,y,m,d,done=0;
  x=Math.abs(x1);
  y=Math.abs(y1);
  m=(y2-y1)/(x2-x1);
  d=x1>x2?"-":"+";
  c=y1-(m*x); // trigonometry

  while (!done) {
   mkDot(x,y,color);
   if (x==x2) { done = 1; }
   if (d=="-") { x--; }
   else { x++; }
   y = parseInt(m*x) + c; // trigonometry
  }
}

window.onload = function() { // only can call after the body loaded
  drawLine(10,40,1000,320,"#3388cc");
};

</script>

<body>
...
</body>

</html>


In case you need the dummy1x1.png, here it is https://drive.google.com/file/d/0B2RFpjH4zL5bTm9TdVo3UFUzRTg/edit?usp=sharing.





My second version (without discontinued steep line problem):



<script>

function drawLine3(x1,y1,x2,y2,color) {

 var x,y,i,m,steep,d,done=0;
 x1=Math.abs(x1);x2=Math.abs(x2);y1=Math.abs(y1);y2=Math.abs(y2);
// make sure no negative points

 if (x1>x2) { // swap xy if 1st point is on the right
  i=x1;x1=x2;x2=i;
  i=y1;y1=y2;y2=i;
 }
 d = y1>y2?1:0; // d = downward
 x=x1;
 y=y1;
 m=(y2-y1)/(x2-x1);
 c=y1-(m*x);
 steep=Math.abs(m)>1?1:0; // if steep, draw more y pixels, else more x pixels

 while (!done) {
  mkDot(x,y,color);
  if (steep) {
   if (y==y2||x==x2) { done = 1; }
   d?y--:y++;
   x = parseInt((y - c)/m);
  }
  else {
   if (x==x2) { done = 1; }
   x++;
   y = parseInt(m*x) + c;
  }
 }
}

</script>



I've just used this improved version to draw this! (Of course with a lots of other codes such as JSON parsers/generator... sent from mySQL chart data) Isn't it cool?



Read More »

Friday, August 15, 2014

Javascript to Prevent Selecting Texts on Tabled Buttons


It is now a common phenomenon that HTML tables are made buttons to replace conventional image-based buttons. The benefits of tabled buttons are quick loading, good button quality when zoomed on tablets and easy to change color. There is also no need to perform pre-loading.

This new popular method of displaying buttons can sometimes perform awkwardly if the text selection is not turned off on the tabled button. The following shows my javascript of disabling the text selection on a table.


<table>
<tr>

<td width=100 bgcolor=yellow id=box1 onclick="func1()" onmouseover="over(this)" onmouseout="out(this)" align=center>Box 1</td>
<td width=100 bgcolor=yellow id=box2 onclick="func2()" onmouseover="over(this)" onmouseout="out(this)" align=center>Box 2</td>

</tr>
</table>

<script>

document.getElementById('box1').onselectstart = function() {return false;};

function func1() {
 alert('Box 1');
}

function func2() {
 alert('Box 2');
}

function over(elem) {
 elem.style.backgroundColor = "#ccddff";
 elem.style.cursor = "pointer";
}

function out(elem) {
 elem.style.backgroundColor = "yellow";
 elem.style.cursor = "default";
}


</script>


The screen capture of this HTML being run on browser:



Note that if your mouse is trying to select on "Box 1", it won't work. But it works for "Box 2", as the selection feature is not disabled by the Javascript.
Read More »

Thursday, August 14, 2014

How to Quickly Identify Missing/Extra HTML Tag

When your HTML gets more and more complicated and packed, a slight mistake in the tagging will render you helpless. It could take a long time to find just a missing or extra tag. My way of solving this problem is to use Notepad++! It's free but it is only available on Windows.


It's easy. You just need to click on the tag and look for missing PURPLE! Once you click on any of the HTML tag, the corresponding closing/opening tag will be highlighted in purple. If you click on a tag and nothing happens, that means Notepad++ is unable to find a corresponding tag for it. You've found the problematic tag! There are still chances that the highlighted tag in purple is wrong. That means you need to also double check the highlighted tag to see whether they are coded the way you really intended.

The screen capture shows the tag highlighted in purple after you click on it. There you have it and happy debugging!

Read More »

Thursday, August 7, 2014

Javascript to Measure Vertical Scrollbar Width


I used the following codes to measure the vertical scrollbar (overflowY) width so that I can place a dummy blank DIV onto the real scrollbar to prevent someone from scrolling by dragging the scroller on the right scrollbar.


<script>

var dummyDiv = document.createElement("div"); // Create a dummy DIV
dummyDiv.style.overflow = "scroll"; // force it to have a scrollbar
dummyDiv.style.width = "50px"; // required for IE, can be other values
document.body.appendChild(dummyDiv); // add to DOM
var scrollbarWidth = dummyDiv.offsetWidth - dummyDiv.clientWidth; document.body.removeChild(dummyDiv); // remove dummy from DOM

alert("The scrollbar width is "+scrollbarWidth);

// If I'm not mistaken, for non IE browsers,
// except the Mac Safari (scrollbars are of 0 width) and touch devices
// such as iPad and tablets, the width is required to increase by 1



</script>


There is a very rare chance that you might need this as most developers nowadays are using JQUERY to take care of the scrolling actions. In case you are a Javascript guy, this is good to know.

Read More »

Monday, July 28, 2014

My Javascript Way to Check the Validity of an Email Address Input



Before sending an email address input from a submitted form to the server to verify, it is better to perform a simple check on the email address format for any possible typo. This will save some server bandwidth as Javascript is capable of catching some obvious email format errors.

The following Javascript codes/function are used:


<script>

function emailError() {

 if (document.userForm.em.value.match(/(\w+\@\w+\.\w+)/) == null) {
  return true;
 }

 return false;
}

if (emailError()) { alert('Invalid Email Format!'); }

</script>


Assume the name of your HTML form is 'userForm' and em is the name of the email input. The emailError() function is making use of the Javascript .match() function to match the pattern of \w+\@\w+\.\w+. If there is a mismatch, an error (true) will be returned to signify an email format error. Please also note that this function will also treat ab.cd@efghijk.xyz as valid although the code can only match the cd@efghijk.xyz. Since the match content is not important, the ab. before the cd will be ignored without affecting the result of the emailError() function.

Read More »

Sunday, July 27, 2014

Javascript to Disable Mouse Scroll for All Browsers including IE


I use these codes to temporarily disable the mouse scroll when I display a pop-up DIV. Although this is not quite necessary but it looks more professional to have mouse scroll locked when the pop-up appears. However the side scroll bar is still working with these following codes. You can still use the mouse to drag the page upward or downward.

The following javascript codes/functions are used: (to lock mouse scroll only that uses the center wheel of a mouse)


<script>

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

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

function lockScroll() {
 if (document.attachEvent) {
   document.attachEvent("on"+mousewheelevent, catchWheel);
 }
 else if (document.addEventListener) {
   document.addEventListener(mousewheelevent, catchWheel, false);
 }
// you can also hide the scrollbar by using the following simple javascript command:
// document.body.style.overflowY="hidden";

}

function unlockScroll() {
 if (document.detachEvent) {
   document.detachEvent("on"+mousewheelevent, catchWheel);
 }
 else if (document.removeEventListener) {
   document.removeEventListener(mousewheelevent, catchWheel, false);
 }
// you can also recover the scrollbar by using the following simple javascript command:
// document.body.style.overflowY="scroll";

}


function catchWheel(e){

 if (e.preventDefault) {
  e.preventDefault();
 }
 else {
  e.returnValue = false;
 }
}


lockScroll(); // to lock scroll
unlockScroll(); // to unlock scroll


</script>


Read More »

Saturday, July 26, 2014

Javascript Way to Check Loaded Image


I use this to display images only after they are loaded into the browser's memory. I need Javascript codes to tell me if the image is ready to be displayed or processed. For example, there is a huge image that I need to display but the size is too big. I display a loading icon before I reveal the image so that it looks more like a contemporary (jQuery equipped) web page. I use the following Javascript codes.


<script>

var loaded_img = new Array();
var image_list = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"); // the list of potential images that you want to check later
var img1loaded = false;

function installOnloadAlarm() {

 var i;
 for (i=0; i<image_list.length; i++) { // iterate all images

  var img = new Image(); // create an image object

  img.onload = function() { // set up onload actions
   var match_result = this.src.match(/\/(\w+\.\w+)$/); // match filename after the last '/'
   loaded_img.push(match_result[1]); // push match result into loaded_img array
  };

  img.src = "image/"+image_list[i]+".jpg"; // by setting the source, the browser will start loading (assume images are in 'image' directory)
 }
}

function checkLoadedImg(imgFilename) {
 var i;
 for (i=0; i<loaded_img.length; i++) {
  if (imgFilename == loaded_img[i]) {
   return true;
  }
 }
 return false;
}

function afterLoaded() {
 if (img1loaded) {
  clearInterval(timer1);
  clearInterval(timer2);
  .
  .
  .
  do your post loading job
  .
  .
  .
 }
}

installOnloadAlarm();
var timer1 = setInterval(function(){img1loaded = checkLoadedImg('1.jpg');},200); // need to set timer to check as the result won't be available instantly (this example checks only '1.jpg')
var timer2 = setInterval(function(){afterLoaded();},200);


</script>


The timers are necessary as the results won't be available after installing the onload conditions. This is just a brief example of a complete image file checking system whether the image is loaded into browser.

Read More »

Wednesday, July 23, 2014

IE4-7 Jagged Text Problem After Applying Filter and the Solution


IE4 until IE7 is notorious to have this anti-alias being turned off after applying a filter to a text (with the position property is set to absolute) such as the opacity filter used for fade in and fade out. For example, the following HTML codes will show the jagged text (without anti-alias) after even applying an empty filter in IE7:

<span id="test" style="position:absolute;top:10px;left:10px;">Remove Filter</span>

<script>
document.getElementById('test').filter = "";
</script>


In order to tell IE4-7 to turn the anti-alias back on, the filter has to go by removing it from the DOM.

<span id="test" style="position:absolute;top:10px;left:10px;">Remove Filter</span>

<script>
document.getElementById('test').filter = "";
document.getElementById('test').style.removeAttribute("filter");
</script>


There you go. The removeAttribute() has to be used to clear the element of any filter. Setting the filter to none still make IE4-7 think that the filter feature will still be needed and you just disable it temporarily.

Read More »

Friday, February 7, 2014

Detecting Browser's Touch Capability Using Javascript


Since the beginning of 2014, Google Chrome returns TRUE on document.createEvent("TouchEvent") javascript call even the browser doesn't support any touch action. The following shows the function I've been using to sniff the touch capability and it is no longer working on the latest Google Chrome:

<script>

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

</script>


The following is the modified version to solve the latest Chrome browser on the touch sniffing function:

<script>

function is_touch_device() {

 var touch = 'ontouchstart' in window;
 return touch?true:false;

}

</script>


The sudden change in support for Chrome is a bit of a surprise to me though.

Read More »

Wednesday, February 5, 2014

Guessing the Performance of Your Browser and Device Using Javascript

After coming out with the Javascript to guess the CPU speed previously, I discovered that the for-next looping codes are not enough to guess the performance of a device/browser.

I realized the looping is only good to guess the performance of the browser, it is not enough to guess the speed of the animation which is crucial in today's web presence.

I then came out with two sets of codes to assess the performance of the animation capability of a device of the browser. One is to test the moving of <SPAN> element, and the other is to test the performance of varying opacity of an element. Here are the codes:

<script>

var count1,d1,startTime1,endTime1,myLatency1;
var count2,d2,startTime2,endTime2,myLatency2;
var count3,d3,startTime3,endTime3,myLatency3;

function getSpeed() {

  var i,j;

  count1 = 0;
  d1 = new Date();
  startTime1 = d1.getTime();

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

  d1 = new Date();
  endTime1 = d1.getTime();
  myLatency1 = endTime1 - startTime1;

  document.getElementById('result').innerHTML = myLatency1;

  d2 = new Date();
  startTime2 = d2.getTime();

  moveSpan();

  d2 = new Date();
  endTime2 = d2.getTime();
  myLatency2 = endTime2 - startTime2;

  document.getElementById('result2').innerHTML = myLatency2;

  d3 = new Date();
  startTime3 = d3.getTime();

  for (j=0; j<8; j++) {
   changeOpacity();
  }

  d3 = new Date();
  endTime3 = d3.getTime();
  myLatency3 = endTime3 - startTime3;

  document.getElementById('result3').innerHTML = myLatency3;
}


function moveSpan() {
  var i;
  for (i=0; i<1000; i++) {
   document.getElementById('dummy').style.left = i+'px';
  }
  for (i=1000; i>-1; i--) {
   document.getElementById('dummy').style.left = i+'px';
  }
  for (i=0; i<1000; i++) {
   document.getElementById('dummy').style.left = i+'px';
  }
  for (i=1000; i>-1; i--) {
   document.getElementById('dummy').style.left = i+'px';
  }

}


function changeOpacity() {
  var i;
  for (i=0; i<10; i++) {
   document.getElementById('dummy').style.MozOpacity = i/10;
   document.getElementById('dummy').style.opacity = i/10;
   document.getElementById('dummy').style.filter = 'alpha(opacity=' + i*10 + ')';
  }
  for (i=10; i>-1; i--) {
   document.getElementById('dummy').style.MozOpacity = i/10;
   document.getElementById('dummy').style.opacity = i/10;
   document.getElementById('dummy').style.filter = 'alpha(opacity=' + i*10 + ')';
  }
}

function startMeasure() {
 setInterval("getSpeed()",500);
}


</script>

<body onload="startMeasure()">
<span id="dummy" style="background-color:#aabbcc;width:50px;height:50px;position:absolute"></span>
<br><br>
<font size=6>Your browser's Javascript Performance index is <font color=green><b><span id=result></span></b>.</font><br>
Your broswer's Animation Performance index is <font color=green><b><span id=result2></span></b>.</font><br>
Your broswer's Opacity Performance index is <font color=green><b><span id=result3></span></b>.</font></font>
</body>



Please note that you can modify the codes to iterate the looping more often if your device is of very high performance. For the devices I tested, as long as the index is less than 15, your device is capable of performing most of the animations you need without much problem. For those with higher numbers, the device may experience some speed problem when it comes to animation running with the browser.

Please also note that you need to assess the opacity and animation performance separately as I encountered vast speed variations for these two actions using different devices especially smartphones and tablet devices.

You can also calculate the average score for each test to get a accurate assessment of the target device. For example, you may decide to run less complicated animations if you get a high score (high latency) for the device.

Enjoy!
Read More »

Wednesday, January 22, 2014

Screen Width and Height for iPhone, iPad, Android Tablets and Smartphones Using Javascript


When it comes to screen width and height, it is a bit tricky for tablet devices as the width and height vary according to the orientation of the tablet.

Therefore it is crucial to detect the screen dimension for websites that are sensitive to the width and height of the screen such as the sticky notes on the web page. The sticky note usually has to be accurate on the location on the web page or it may block important information in the web site.





The following are the Javascript codes that I used:

<script>

var clientWidth = document.getElementsByTagName("body")[0].clientWidth;
var clientHeight = document.getElementsByTagName("body")[0].clientHeight;
.
.
.
</script>


However, there is a problem here. The width and height will change whenever the user changes the orientation of the tablet. Here are improved codes after taking such scenario into consideration:

<script>

function checkDimension() {
   var clientWidth = document.getElementsByTagName("body")[0].clientWidth;
   var clientHeight = document.getElementsByTagName("body")[0].clientHeight;
.
.
.

</script>

<body onresize="checkDimension()"> .
.
.



Whenever the tablet changes the orientation, the onresize event on the browser will go to checkDimension() function. In that case, the Javascript is able to react to any changes to screen size and orientation.

Read More »

Monday, January 20, 2014

Strange Tablet (Touch Device) Problem with Javascript's MarginLeft/MarginRight DOM property


This is really hard to explain. If you do your coding in Javascript to move a DIV/SPAN manipulating the value in marginLeft/marginRight DOM property, you will run into a problem that your touch devices, ie., iPad, Android tablet/smartphones won't work with this trick if you have a align=center property somewhere before the DIV/SPAN.

Foe example:

.
.
.

<table><tr><td align=center><div id=moveDiv>...</div></td></tr></table>

<script>
document.getElementById('moveDiv').style.marginLeft = "100px";
</script>


The above code will work on any desktop browser but won't work on any touch capable devices such iOS/Android tablet or smartphone. Strange? Of course, when you have the align=center statement removed, things will work flawlessly in any device.

Read More »

Preload Images using Javascript


There are times that you need to preload images on your web page to avoid the long load time required for a dynamic HTML site.

I've tried many examples found on the web but none of them are really working on today's browsers.

Here's my way of making this happen:

<script>

var image_loc = new Array('/image/pic1.jpg','/image/pic5.jpg','/image/pic13.jpg','/image/pic9.jpg');
var elem;

for (i = 0; i < image_loc.length; i++) {
   elem = document.createElement("span");
   elem.id = "preload_img"+i; // this is optional
   elem.style.position = 'absolute';
   elem.style.visibility = 'hidden';
   elem.style.left = '0px';
   elem.style.top = '0px';
   elem.style.width = '10px'; // this can be bigger as long as it is not wider than the screen to avoid extra scroll bar appears at the bottom of the window
   elem.style.height = '10px';
   elem.style.background = "url('"+image_loc[i]+"') no-repeat left top";
   document.body.appendChild(elem);
}

</script>


The trick is to create hidden elements and load the images to be preloaded into background. Those images will be hidden and located at the upper left corner of the screen. The location and size of the SPAN element can be of other values. Hope you like my first new trick in 2014!

Read More »