Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Monday, August 28, 2017

Javascript to Limit HTML Width for Mobile Devices of Any Orientation

The viewport parameter in the HTML Meta Tag is used to limit the screen width. Another thing to pay attention for these codes is the neccessity to differentiate between tablets and phones. Phones tend to have less resolution whereas tablets can have resolutions comparable to that of PC or Mac. I use a simple criteria to differentiate the two by checking the screen width whether it is wider than 700 pixels. If so, tablets' width will be forced to limit to only 700 pixels. For non-tablets, the width will be limited to the native screen width found in the Javascript system parameter screen.width. Pay attention to when orientation changes. Android will have the width and height paramters swapped whereas the mobile Safari will have the same width and height irregardless of the orientation.

The <body> onorientationchange is used to listen to the orientation change even. Whenever it is fired, the 'content' meta will be reconfigured according to the orientation status. Javascript's window.orientation is used to check the current orientation status in terms of degrees.

Let's jump into the codes:

<html>
<head>
<title>Javascript to Limit HTML Width for Mobile Devices of Any Orientation</title>

<script>

var mobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i);

var safari = navigator.userAgent.match(/iPhone|iPad|iPod/i) && navigator.userAgent.match(/Safari/i);

var ot = ""; // variable "orientation" is used by mobile browsers
if (safari) {
 if (window.orientation == 0) { ot="portrait"; } else { ot="landscape"; }
}
else {
 if (screen.width<screen.height) { ot="portrait"; } else { ot="landscape"; }
}


if (mobile) {
 var mobileWidth = getMobileWidth();
 alert("setting the width of "+mobileWidth);
 document.write('<meta id="vp" name="viewport" content="width = '+mobileWidth+', initial-scale=1.0">');
}
// if it is not mobile, viewport is not supported or will be ignored

function getMobileWidth() {
 var width;
 var isTablet = 0;
 if (safari) { // safari screen width and height remain constant irregradless of the orientation
  if (ot == "portrait") { width = screen.width; if (width>400) {isTablet=1;} }
  else { width = screen.height; if (width>700) {isTablet=1;} }
 }
 else {
  width = screen.width;
  if (ot == "portrait") { if (width>400) {isTablet=1;} }
  else { if (width>700) { isTablet=1;} }
 }
 if (isTablet) {
  if (ot == "portrait") {
   return 400;
  }
  else {
   return 700;
  }
 }
 else {
  return width;
 }
}

function changeViewPort() { //change viewport dynamically by changing the meta 'content' attribute

 if (safari) { // mobile safari will not swap screen.width with screen.height after orientation change
  if (window.orientation == 0) { ot="portrait"; } else { ot="landscape"; }
 }
 else { // other broswers will have height and width swapped
  if (screen.width<screen.height) { ot="portrait"; } else { ot="landscape"; }
 }

 var mobileWidth = getMobileWidth();
 alert("setting the width of "+mobileWidth);
 alert("screen in "+ot+" mode w:"+screen.width+" h:"+screen.height+" -->"+window.orientation);

 if (mobile) {
  var vp = document.getElementById('vp');
  vp.setAttribute('content','width='+mobileWidth+', initial-scale=1.0');
 }
}

</script>

</head>

<body bgcolor=orange onorientationchange="changeViewPort()">

<table width=100% height=100% align=center valign=middle>
<tr><td width=100% height=100% align=center valign=middle style="font-family: Lucida Sans, Lucida Sans Unicode, Helvetica, Arial, sans-serif;">Under Construction</td></tr>
</table>

</body>

</html>


Please note the meta tag has been given an ID (id="vp") so that it can be modified when necessary. onorientationchange is used instead of "onresize" as "onresize" will make give a lots of false signal even when the address bar in mobile browsers shows up or hides.

Read More »

Tuesday, April 5, 2016

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 »

Monday, March 7, 2016

Limit a DIV to Certain Scroll Height with Javascript

This is very popular nowadays. You can see major websites around the internet are having this feature. Why? Important information will not get left out if the web page is scrolled down a lot. This can improve the navigation experience of the website substantially. So how is it done? You may need to know how to fix a DIV before you can fully understand this post. Here are some of my earlier posts related to this subject:

http://webtrick101.blogspot.my/2015/11/fixing-several-divs-at-same-time-for.html
http://webtrick101.blogspot.my/2015/11/fix- div-on-top-of-page-only-after.html
http://webtrick101.blogspot.my/2015/11/fix-position-of-div-at-bottom-of-page.html

Here are the codes for this post:

<!DOCTYPE HTML>
<html>
<style type="text/css">

#fixbot {
bottom:0px;
position: fixed;
}

#fixright {
right:0px;
position: absolute;
}

#fixtop {
top:0px;
position: fixed;
}

</style>

<script>

var offset;

window.onscroll = function() {

 if (typeof(window.pageYOffset) == 'number') {
  offset = window.pageYOffset;
 }
 else if (document.documentElement) {
  offset = document.documentElement.scrollTop;
 }
 else if (document.body) {
  offset = document.body.scrollTop;
 }
 if (offset > 170) {
  document.getElementById('fixright').style.position = 'fixed';
  document.getElementById('fixright').style.top = '170px';
 }
 else {
  document.getElementById('fixright').style.position = 'absolute';
  document.getElementById('fixright').style.top = '50%';
 }
 document.getElementById('notice').innerHTML = offset;
}

</script>

<body bgcolor="#aabbcc" marginheight=0 marginwidth=0 leftmargin=0 topmargin=0 rightmargin=0 bottommargin=0 onload="window.scrollTo(0,0);">

<div id="fixbot" style="border:0px solid #333; width:100%; height:50px; background-color:#ddd; text-align:center; padding:0px; ">
<p>Hello I am at the bottom!</p>
</div>

<div id="fixright" style="border:0px; width:100px; height:200px; text-align:center; padding:0px; top: 50%; margin-top: -100px; background-color:#cba;">
<table width=100% height=100%><tr><td valign=middle><p>Right!</p></td></tr></table>
</div>

<div id="fixtop" style="border:0px solid #333; width:100%; height:70px; background-color:#ddd; text-align:center; padding:0px; "> <p>Hello I am at the top! <span id="notice"></span></p>
</div>

<table width="95%" align=center><tr><td>
<br>line 1<br>line 2<br>line 3<br>line 4<br>line 5<br>line 6<br>line 7<br>line 8<br>line 9<br>line 10 <br>line 11<br>line 12<br>line 13<br>line 14<br>line 15<br>line 16<br>line 17<br>line 18<br>line 19<br>line 20 <br>line 21<br>line 22<br>line 23<br>line 24<br>line 25<br>line 26<br>line 27<br>line 28<br>line 29<br>line 30 <br>line 31<br>line 32<br>line 33<br>line 34<br>line 35<br>line 36<br>line 37<br>line 38<br>line 39<br>line 40 <br>line 41<br>line 42<br>line 43<br>line 44<br>line 45<br>line 46<br>line 47<br>line 48<br>line 49<br>line 50 <br>line 51<br>line 52<br>line 53<br>line 54<br>line 55<br>line 56<br>line 57<br>line 58<br>line 59<br>line 60 <br>line 61<br>line 62<br>line 63<br>line 64<br>line 65<br>line 66<br>line 67<br>line 68<br>line 69<br>line 70 </td></tr></table>

<script>
setTimeout(function() {window.scrollTo(0, 0);},100); // To make sure when the page is reloaded, the scroll is back to 0
document.getElementById('fixright').style.top = '50%';

</script>

</body>
</html>




In order to position a DIV on the middle of the right hand side, I prepare the DIV to be always 50% of the total height and the - 100px margin (derived from half of the total height of the DIV which is 200px in this case). In this example, I want to fix the right hand DIV to be exactly 70x from the top of the page. I need to let the Javascript to do the job for me by checking the mouse scroll offset. The magic 170px limit can be obtained from adding the half of the total height of the DIV with the target height limit.



The Javascript will detect the scroll offset if it crosses the 170px marking I set. If it is more than the 170px limit, fix the DIV. If it is less, let it scroll as it should be but maintain the 50% position relative to the viewable height of the website window.



One thing to pay attention is when the page is reloaded, the scroll has to go back to 0 or the calibration of the mechanism of these will be off. If this is not desired, one can consider resorting to cookie to track the relative position of the DIV and scroll offset. This is a head start to such new web feature. More complex feature can still be incorporated into these codes such as managing a very long (high) DIV. Enjoy!

Here is the animated demonstration of this example:



Read More »

Thursday, December 31, 2015

Simple Captcha Verification Using Javascript and PHP with GD Lib


This is a simple version that uses minimal amount of codes. However, this practice is not suitable for websites that require stringent security protection.

The PHP codes make use of the GD library to generate a PNG image file that will be read by the HTML code. The PHP will randomly generate two characters and two numbers with first digit as character followed by a number, then a character and a number. Of course, you can change it to something more complicated like making it a mathematical problem to be solved by the visitor. The PNG image will be accompanied by a browser cookie with the answer to the captcha. The cookie will then be compared with the input by the user to see if they match. You can also send the answer back to the server to be verified in order to make it more secure. However, it is not the scope of this example as I try to make it as simple as possible so that it is easy to understand.

Here are the PHP codes:

<?php

// I name this file captcha.php
error_reporting(0); // this is important to turn off all the warnings if any

session_start();

$angle = rand(-10,10);
$fontSize = 20;

$captchaText = chr(97 + rand(0, 25)).rand(0,9).chr(97 + rand(0, 25)).rand(0,9);


$img = imagecreatetruecolor(120, 50);
$bgColor = imagecolorallocate($img, rand(50,150), rand(50,150), rand(50,150)); //background color - random dark coolor
$fgColor = imagecolorallocate($img, rand(200,255), rand(200,255), rand(200,255)); //foreground color - random light color
imagefill($img, 0, 0, $bgColor);

imagettftext($img, $fontSize, $angle, 25, 35, $fgColor, "./LiberationSerif-Bold.ttf", $captchaText);

setcookie("randomCharacterCookieName", $captchaText, time()+3600, '/'); // will expire in one hour

header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);

?>


Make sure your PHP has the GD library support before you proceed.

The tricky part is the one highlighted in red. You need to upload a font to your home directory to make this PHP script to work. Why don't we use the server font? Most of the time, the shared server won't have any TrueType font in it or the GD doesn't have the authority to run it. It is still better to upload your own font and you have more choice for the font as well. I chose the Liberation font as it is royalty free. You can change to your own font if you prefer.

And now comes the Javascript and HTML:

<html>

<script>

function checkCaptcha() {
 var ans = document.getElementById('answer').value;
 var tmp = document.cookie;
 var chunk = tmp.split('=');
 if (chunk[chunk.length-1] == ans) {
  alert("yes!");
  // proceed with your post verification codes such submitting the form etc.
 }
 else {
 alert("no!");
 }
}

</script>

<body>
<img src="captcha.php">
<br>
Type what you see above here:
<br>
<input type="text" id=answer size=4 maxlength=4> <a href="javascript:checkCaptcha()">Check</a>

</body>

</html>


After running the HTML, I captured this response from Chrome after a right answer is entered:



I captured this response from Chrome after entering a wrong answer purposely:



There are still many things you can improve from these codes. For example, you can still include capital letter or even some special characters to the captcha. You can also scramble the answer in the cookie and descramble it during verification with the answer embedded in the cookie.

Well, here is the Captcha tutorial! Finally!

Read More »

Tuesday, December 29, 2015

Sending Multiple MySQL Table Data from PHP to Javascript via AJAX


Note: Please run these codes from a web host, either it is a "localhost" or remote host from a web hosting server.

This is an expansion of my earlier post with sending data from only one MySQL table. For multiple table data channeling to browser from MySQL, a query string is used to differentiate the AJAX requirement. You can also create another PHP script to access data from other tables but it seems quite unnecessary as it can be easily achieved by sending different query strings to the AJAX PHP script.

Here we go again:

USE `testDB`;
DROP TABLE IF EXISTS `test`;

CREATE TABLE `test` (
 `a` tinyint(4) DEFAULT NULL,
 `b` tinyint(4) DEFAULT NULL,
 `c` tinyint(4) DEFAULT NULL,
 `d` tinyint(4) DEFAULT NULL,
 `e` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `test2`;

CREATE TABLE `test2` (
 `f` tinyint(4) DEFAULT NULL,
 `g` tinyint(4) DEFAULT NULL,
 `h` tinyint(4) DEFAULT NULL,
 `i` tinyint(4) DEFAULT NULL,
 `j` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into `test`(`a`,`b`,`c`,`d`,`e`) values (1,2,3,4,5),(6,7,8,9,10),(11,12,13,14,15),(16,17,18,19,20);
insert into `test2`(`f`,`g`,`h`,`i`,`j`) values (21,22,23,24,25),(26,27,28,29,30),(31,32,33,34,35),(36,37,38,39,40);


A new table 'test2' is added to the previous table setup (refer to my earlier post to check out the difference).

Here are the PHP codes for AJAX (or act as a JSON data generator):

<?php
 //I name this file ajax.php
 error_reporting(0);
 $db_name = "testDB";
 $db_server_name = "localhost";
 $db_usr_name = "xxxx"; // Please replace xxxx with your MySQL username
 $db_pw = "xxxxxxxx"; // Please replace xxxxxxxx with the password that came with it

 $dblink = mysql_connect($db_server_name, $db_usr_name, $db_pw);

 if (!$dblink) {
  array_push($error, "Failed to Connect to Database");
 }
 mysql_select_db($db_name);

 if ($_GET['tbl'] == '1') {
  $query = mysql_query("SELECT * from test");
 }
 else if ($_GET['tbl'] == '2') {
  $query = mysql_query("SELECT * from test2");
 }

 $all = array();

 $d = 0;
 while ($query_result = mysql_fetch_assoc($query)) {
  if ($_GET['tbl'] == '1') {
   $all[$d] = array("a"=>$query_result['a'],"b"=>$query_result['b'],"c"=>$query_result['c'],"d"=>$query_result['d'],"e"=>$query_result['e']);
  }
  else if ($_GET['tbl'] == '2') {
   $all[$d] = array("f"=>$query_result['f'],"g"=>$query_result['g'],"h"=>$query_result['h'],"i"=>$query_result['i'],"j"=>$query_result['j']);
  }
  $d++;
 }

 $encoded = json_encode($all);
 header('Content-type: application/json');
 exit($encoded);

?>


Finally here are the Javascript codes:

<!DOCTYPE html>
<html>

<script>

var data;

function loadJSON(path) {

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
   if (xhr.status === 200) {
    try {
     data = JSON.parse(xhr.responseText);

     for (var k in data) {

      alert(data[k].a+" "+data[k].b+" "+data[k].c+" "+data[k].d+" "+data[k].e);


    }
    catch(e) {
     alert("Data Error. Please contact the administrator.");
    }
   }
   else {
    console.error(xhr);
   }
  }
 };
 xhr.open("GET", path, true);
 xhr.send();
}

function loadJSON2(path) {

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
   if (xhr.status === 200) {
    try {
     data = JSON.parse(xhr.responseText);

     for (var k in data) {

      alert(data[k].f+" "+data[k].g+" "+data[k].h+" "+data[k].i+" "+data[k].j);


    }
    catch(e) {
     alert("Data Error. Please contact the administrator.");
    }
   }
   else {
    console.error(xhr);
   }
  }
 };
 xhr.open("GET", path, true);
 xhr.send();
}

loadJSON('ajax.php?tbl=1'); // This result will be the same as in the earlier post
loadJSON2('ajax.php?tbl=2'); // tell ajax.php that $_GET['tbl'] = 2;

</script>

The data from MySQL will prompt out as alerts, row by row.

</html>


Please note that the DOCTYPE declaration is important for IE browsers as it puts it into standards mode for AJAX to work.

You can also combine loadJSON with loadJSON2 by adding one more parameter to the function. Anyway, to make explanation less confusing, I added another JSON loading function to it.

After running the codes, you may get four alerts with the first time being '1 2 3 4 5' followed by '6 7 8 9 10' and so forth as in the earlier post. Then you may get the new alerts from the second table. Here is a screen shot of the first prompt from the second table running in Chrome:



Caveat: The data from the second table may prompt up before the first table. If you really want to make sure the first table come first, you will need to use the timer to delay the loadJASON2 function a bit.

Thanks for viewing!
Read More »

Friday, December 25, 2015

Sending MySQL Data from PHP to Javascript via AJAX


This is done through AJAX. It should be well supported by most browsers including IE. Everything is quite straight forward. First you need to set up a dummy MySQL database to test out the following javascripts. Here is the SQL to set the database up:

USE `testDB`;
DROP TABLE IF EXISTS `test`;

CREATE TABLE `test` (
 `a` tinyint(4) DEFAULT NULL,
 `b` tinyint(4) DEFAULT NULL,
 `c` tinyint(4) DEFAULT NULL,
 `d` tinyint(4) DEFAULT NULL,
 `e` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into `test`(`a`,`b`,`c`,`d`,`e`) values (1,2,3,4,5),(6,7,8,9,10),(11,12,13,14,15),(16,17,18,19,20);



The above SQL uses a database called 'testDB' with a table named 'test'. The 'test' table came with 5 columns namely 'a', 'b', 'c', 'd' and 'e'. Four rows of data are inserted with number incremented by one starting from 1. The first row contains 1, 2, 3, 4 and 5. The second row starts from 6 until 10 and so forth.

Here are the PHP codes for AJAX (or act as a JSON data generator):

<?php
 //I name this file ajax.php
 error_reporting(0);
 $db_name = "testDB";
 $db_server_name = "localhost";
 $db_usr_name = "xxxx"; // Please replace xxxx with your MySQL username
 $db_pw = "xxxxxxxx"; // Please replace xxxxxxxx with the password that came with it

 $dblink = mysql_connect($db_server_name, $db_usr_name, $db_pw);

 if (!$dblink) {
  array_push($error, "Failed to Connect to Database");
 }
 mysql_select_db($db_name);

 $query = mysql_query("SELECT * from test");

 $all = array();

 $d = 0;
 while ($query_result = mysql_fetch_assoc($query)) {
  $all[$d] = array("a"=>$query_result['a'],"b"=>$query_result['b'],"c"=>$query_result['c'],"d"=>$query_result['d'],"e"=>$query_result['e']);
  $d++;
 }

 $encoded = json_encode($all);
 header('Content-type: application/json');
 exit($encoded);

?>


Finally here are the Javascript codes:

<!DOCTYPE html>
<html>

<script>

var data;
var saveArr1 = new Array();
var saveArr2 = new Array();

function loadJSON(path) {

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
   if (xhr.status === 200) {
    try {
     data = JSON.parse(xhr.responseText);

     for (var k in data) {

      alert(data[k].a+" "+data[k].b+" "+data[k].c+" "+data[k].d+" "+data[k].e);

      // saveArr1.push(k); // if you want to save the array key to an array called saveArr1
      // saveArr2.push(data[k].b); // if you want to save the array data column 'b' to an array called saveArr2

     }
     // alert(data.length); // if you want to check the total length

    }
    catch(e) {
     alert("Data Error. Please contact the administrator.");
    }
   }
   else {
    console.error(xhr);
   }
  }
 };
 xhr.open("GET", path, true);
 xhr.send();
}

loadJSON('ajax.php?set=1'); // '?set=1' is optional and your PHP codes will receive this parameter as $_GET['set'] in PHP

</script>

The data from MySQL will prompt out as alerts, row by row.

</html>


Please note that the DOCTYPE declaration is important for IE browsers as it puts it into standards mode for AJAX to work.

After running the codes, you will get four alerts with the first time being '1 2 3 4 5' followed by '6 7 8 9 10' and so forth. Here is a screen shot of the first prompt running in Chrome:



Please let me know if you encounter any problem with these codes. I will be happy to answer any questions that you may have. Enjoy!
Read More »

Monday, December 21, 2015

Casting a Reflection Image Using Pure Javascript


This is mainly for fun or educational purposes only. This is inspired by a carousel javascript plugin with reflection at the bottom of each image which looks like they are standing on a solid marble. Since it is an awesome idea, I tried to do some coding if it is able to be done by just pure Javascript. Yes, they are done and the codes are presented as follows:

<html>
<body>


<a href="javascript:renderReflection()">Render Reflection</a>
<br><br>

<script>

var height,width;
var tmpDiv,tmpDiv2,i,j,k,l,m,n;
var img = new Image();
var file = 'img/phone_icon2.png';
img.src = file;
img.onload = function() {
 height = this.height;
 width = this.width;
}

tmpDiv = document.createElement("span");
tmpDiv.innerHTML = '<img id=img0 src="'+file+'">';
tmpDiv.style.position = 'absolute';
tmpDiv.style.left = '300px';
tmpDiv.style.top = '150px';
tmpDiv.id = "imgSpan";
document.body.appendChild(tmpDiv);


function renderReflection() {

 k=0, l=-0.25, m=50, n=1; // n=speed of fade, // m=percentage of fade, // l=reflection direction

 for (i=1; i<=height; i++) {
 tmpDiv = document.createElement("span");
 tmpDiv.id = "line"+i;
 tmpDiv.style.height = '1px';
 tmpDiv.style.width = width+'px';
 tmpDiv.style.position = 'absolute';
 tmpDiv.style.overflow = 'hidden';

 j = i*n+(height*((100-m)/100));
 if (j>height) { j=height; }

 tmpDiv.style.MozOpacity = ((height-j+1)/height*10)/10;
 tmpDiv.style.opacity = ((height-j+1)/height*10)/10;

 tmpDiv2 = document.createElement("span");
 tmpDiv2.innerHTML = '<img id=img'+i+' src="'+file+'">';
 tmpDiv2.style.position = 'absolute';
 tmpDiv2.style.marginTop = -1*(height-i-1)+'px';
 tmpDiv2.style.filter = 'alpha(opacity=' + Math.round((height-j+1)/height*100) + ')';

 k+=l;

 tmpDiv.style.left = document.getElementById('imgSpan').offsetLeft + k + 'px';
 tmpDiv.style.top = height + document.getElementById('imgSpan').offsetTop + i + 'px';
 tmpDiv.appendChild(tmpDiv2);
 document.body.appendChild(tmpDiv);

 }
}

</script>

</body>
</html>


You can adjust the style of the reflection by changing the value for l, m or n.

l is the control of the direction for the reflection. A negative value will move the reflection to the left and a postive value will move it to the right. A zero value will cast the reflection straight down.

m is the percentage of the reflection to be rendered. A value of 50 will only allow a maximum 50% of the reflection to be shown. The reflection image will look like being cut into half.

n is the fading speed of the reflection image. A value of 2 will double up the fading speed which result in only half of the reflection image being rendered. A value of 3 will triple up the fading speed which result in only a third of the reflection image being rendered.

The following is the screen capture of the trial runs.

The result of k=0, l=-0.25, m=50, n=1:





The result of k=0, l=0, m=100, n=1.25:





The result of k=0, l=1, m=85, n=2:





You can change the file name and path to something else by modifying var file = 'img/phone_icon2.png';! Enjoy!

P.S.: You need to click on the Render Reflection link to run the reflection rendering function in case you are not aware of.

Read More »

Monday, November 30, 2015

Pop a Message Box in the Center with Freezing and Hiding the Scrollbar

This is the continuation of the previous post with also the codes to freeze the mouse scroll and hide the scroll bar. This is crucial to lock on a page to avoid any scrolling events after a message box popped up to demand a better attention from the visitor. Basically the codes are just added with a the scroll-locking codes I posted earlier here. In addition to that, I included the scrollbar disabling javascript "document.body.style.overflowY = 'hidden';" code. Here are the long combined codes:

<!DOCTYPE HTML>
<html>

<style type="text/css">

#curtain {
left:0px;
top:0px;
filter:alpha(opacity=70);
-moz-opacity:0.7;
opacity:0.7;
width: 100%;
height: 100%;

}

#message_box {
left:50%;
top:50%;
width: 200px;
height: 70px;
z-index: 1;
margin-top: -35px;
margin-left: -100px;
}

div > div#curtain { position: fixed; }
div > div#message_box { position: fixed; }

</style>

<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);
 }

}

function unlockScroll() {
 if (document.detachEvent) {
  document.detachEvent("on"+mousewheelevent, catchWheel);
 }
 else if (document.removeEventListener) {
  document.removeEventListener(mousewheelevent, catchWheel, false);
 }

}


function catchWheel(e){

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


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


function close() {
 document.body.style.overflowY = 'scroll';
 document.getElementById('curtain').style.visibility = "hidden";
 document.getElementById('message_box').style.visibility = "hidden";
 unlockScroll();
}

function open() {
 document.body.style.overflowY = 'hidden';
 document.getElementById('curtain').style.visibility = "visible";
 document.getElementById('message_box').style.visibility = "visible";
 lockScroll();
}


lockScroll();

</script>


<body bgcolor="#aabbcc">


<div style="width:100%;height:100%;">

<div id="message_box" style="border:1px solid #333; background-color:#ddd; text-align:center; padding:10px; ">
<p>Message Here<br><a href="javascript:close()">Close</a></p>
</div>

<div id="curtain" style="background-color:#ddd;"> </div>

</div>


<table width="95%" align=center><tr><td>
<br><a href="javascript:open()">Show Message Box</a>
<br>line 1<br>line 2<br>line 3<br>line 4<br>line 5<br>line 6<br>line 7<br>line 8<br>line 9<br>line 10
<br>line 11<br>line 12<br>line 13<br>line 14<br>line 15<br>line 16<br>line 17<br>line 18<br>line 19<br>line 20
<br>line 21<br>line 22<br>line 23<br>line 24<br>line 25<br>line 26<br>line 27<br>line 28<br>line 29<br>line 30
<br>line 31<br>line 32<br>line 33<br>line 34<br>line 35<br>line 36<br>line 37<br>line 38<br>line 39<br>line 40
<br>line 41<br>line 42<br>line 43<br>line 44<br>line 45<br>line 46<br>line 47<br>line 48<br>line 49<br>line 50
<br>line 51<br>line 52<br>line 53<br>line 54<br>line 55<br>line 56<br>line 57<br>line 58<br>line 59<br>line 60
<br>line 61<br>line 62<br>line 63<br>line 64<br>line 65<br>line 66<br>line 67<br>line 68<br>line 69<br>line 70
</td></tr></table>

<script>document.body.style.overflowY = 'hidden';</script>
</body>

</html>


The scrollbar will reappear after the 'close' button is pressed.

Enjoy!

Read More »

Pop a Message Box in the Center with Transparent Background Curtain using Fixed DIV and CSS


This is a very popular method to pop up a small window at the center of a page to ask for user's registration or something that requires visitors' special attention. The following codes will not freeze the scroll bars or any movement on the page:

<!DOCTYPE HTML>
<html>

<style type="text/css">

#curtain {
left:0px;
top:0px;
filter:alpha(opacity=70);
-moz-opacity:0.7;
opacity:0.7;
width: 100%;
height: 100%;

}

#message_box {
left:50%;
top:50%;
width: 200px;
height: 70px;
z-index: 1;
margin-top: -35px; /* 70/2 * -1 */
margin-left: -100px; /* 200/2 * -1 */
}

div > div#curtain { position: fixed; }
div > div#message_box { position: fixed; }

</style>

<script>

function close() {
document.getElementById('curtain').style.visibility = "hidden";
document.getElementById('message_box').style.visibility = "hidden";
}


</script>


<body bgcolor="#aabbcc">


<div style="width:100%;height:100%;">

<div id="message_box" style="border:1px solid #333; background-color:#ddd; text-align:center; padding:10px; ">
<p>Message Here<br><a href="javascript:close()">Close</a></p>
</div>

<div id="curtain" style="background-color:#ddd;"> </div>

</div>



<table width="95%" align=center><tr><td>
<br>line 1<br>line 2<br>line 3<br>line 4<br>line 5<br>line 6<br>line 7<br>line 8<br>line 9<br>line 10
<br>line 11<br>line 12<br>line 13<br>line 14<br>line 15<br>line 16<br>line 17<br>line 18<br>line 19<br>line 20
<br>line 21<br>line 22<br>line 23<br>line 24<br>line 25<br>line 26<br>line 27<br>line 28<br>line 29<br>line 30
<br>line 31<br>line 32<br>line 33<br>line 34<br>line 35<br>line 36<br>line 37<br>line 38<br>line 39<br>line 40
<br>line 41<br>line 42<br>line 43<br>line 44<br>line 45<br>line 46<br>line 47<br>line 48<br>line 49<br>line 50
<br>line 51<br>line 52<br>line 53<br>line 54<br>line 55<br>line 56<br>line 57<br>line 58<br>line 59<br>line 60
<br>line 61<br>line 62<br>line 63<br>line 64<br>line 65<br>line 66<br>line 67<br>line 68<br>line 69<br>line 70
</td></tr></table>


</body>

</html>


Here is a screenshot of the HTML ran on a Google Chrome browser:



As for the scroll bars freezing or movement stalling versions, they will be presented in the coming posts. This post is all about the transparent engulfing DIV and the pop-up window at the center of it.

Please note that in order to fix the message box to the center of the page, the margin-top and margin-left CSS properties are used. If these margins are not implemented, the upper left corner of the message box will be at the center of the page. The margin is the negative value of the half of the height or width of the box.

Javascript is also used to hide the message box when the "close" link is clicked. At the same time, the curtain is also removed when the message box is hidden.

Read More »

Monday, November 23, 2015

Fix a DIV on Top of Page Only After Certain Scroll via Javascript

Such web page technique is very popular as of now. When a visitor of your web page scroll down to certain level, a new top panel bar will appear so as to make the page navigation more fluent. This could be inspired by the screen limitation of mobile phones and browsing web pages using a smartphone is a norm these days. Beside the benefit of smoother navigation, the logo of the page can appear more often to increase the logo exposure to the reader.

Here are the codes:

<!DOCTYPE HTML>
<html>
<style type="text/css">

#fixtop {
position: absolute;
top:0px;
}

div > div#fixtop { position: fixed; }
</style>

<script>

var offset;

function checkScrollOffset() {

 if (typeof(window.pageYOffset) == 'number') {
  offset = window.pageYOffset;
 }
 else if (document.documentElement) {
  offset = document.documentElement.scrollTop;
 }
 else if (document.body) {
  offset = document.body.scrollTop;
 }
 if (offset > 0) { // you can choose other values for the trigger if you want the fixed div to appear after more scroll offset value
  document.getElementById('fixtop').style.display = 'block';  }
 else { document.getElementById('fixtop').style.display = 'none'; }

}


</script>


<body bgcolor="#aabbcc" marginheight=0 marginwidth=0 leftmargin=0 topmargin=0 rightmargin=0 bottommargin=0 onscroll="checkScrollOffset()">

<div>

<div id="fixtop" style="border:0px solid #333; width:100%; height:50px; background-color:#ddd; text-align:center; padding:0px; display: none;">
<p>Hello I am here!</p>
</div>

</div>

<table width="95%" align=center><tr><td>
<br>line 1<br>line 2<br>line 3<br>line 4<br>line 5<br>line 6<br>line 7<br>line 8<br>line 9<br>line 10
<br>line 11<br>line 12<br>line 13<br>line 14<br>line 15<br>line 16<br>line 17<br>line 18<br>line 19<br>line 20
<br>line 21<br>line 22<br>line 23<br>line 24<br>line 25<br>line 26<br>line 27<br>line 28<br>line 29<br>line 30
<br>line 31<br>line 32<br>line 33<br>line 34<br>line 35<br>line 36<br>line 37<br>line 38<br>line 39<br>line 40
<br>line 41<br>line 42<br>line 43<br>line 44<br>line 45<br>line 46<br>line 47<br>line 48<br>line 49<br>line 50
<br>line 51<br>line 52<br>line 53<br>line 54<br>line 55<br>line 56<br>line 57<br>line 58<br>line 59<br>line 60
<br>line 61<br>line 62<br>line 63<br>line 64<br>line 65<br>line 66<br>line 67<br>line 68<br>line 69<br>line 70
</td></tr></table>

</body>
</html>


If you are not sure how to fix a DIV using pure CSS, visit my earlier post here or here as it is the basis of this web trick.

You can also make the fixed DIV semi-transparent by applying the opacity filter in the CSS if you wish.

Note: Try to avoid changing the visibility style in CSS to turn on or off the DIV. Use 'display: none' and 'display: block' instead as the visibility property may cause the fixed DIV to flicker while scrolling in Chrome. The reason for the flicker is unknown.

Read More »

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 »

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 »

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 »

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 »