Tag Archives: JavaScript

CSS and JavaScript Animation Remake For Tuas South Incineration Plant Video

What happens if you want to play an old animation video on a modern PC that was created long before FHD and 4K monitors are being invented? Instead of watching the animation, you will be dazed with square pixel boxes and wonder why would the animator likes boxes so much.

This project is a remake of Tuas South Singapore Incineration Plant video using multiple static images, intensive CSS animation and JavaScript for a school environmental hub project. The original animation video belongs to National Environmental Agency (NEA) Singapore.

GitHub: https://github.com/kennykee/Tuas-Incineration-Animation
Demo: https://demo.kennykee.com/MT (View it on the PC)
YouTube: https://www.youtube.com/watch?v=kbaUYNklYxo

PHP HTML Entities String Function For Javascript Function Not Working Solution – Simple Concept

“Uncaught SyntaxError: Unexpected token ILLEGAL” is a common error when input parameter of JavaScript function is not closed properly.

1) To escape JavaScript parameter, we use PHP htmlentities function. However, even with PHP htmlentities, we might still encounter this issue. Consider the following example:

 PHP Code:

echo "<a href='javascript:showContent(\"" . htmlentities ("Edit Service Sushi's Shop", ENT_QUOTES) . "\");'></a>";

2) Now the string should be Edit Service Sushi&apos;s Shop.

3) However, when this string reaches browser, the string gets unescaped and becomes:

<a href='javascript:showContent("Edit Service Sushi's Shop");'></a>

4) Hence, the JavaScript function breaks when user click on this link.

5) To solve this, we need to double-escape the string.

echo "<a href='javascript:showContent(\"" . htmlentities(htmlentities("Edit Service Sushi's Shop", ENT_QUOTES), ENT_QUOTES) . "\");'></a>";

6) Now the string becomes Edit Service Sushi&amp;apos;s Shop. The string parameter is now safe. We can use this parameter string as input for jQuery.html() function without breaking the JavaScript function.

<a href='javascript:showContent("Edit Service Sushi&apos;s Shop");'></a>

<script>
function showContent(input){
   $("#mydiv").html(input); 
   //the escaped characters will be unescaped via .html function
}
</script>

jQuery Images Crossfading Front Page Banner – Simple Stuffs

Creating a crossfading images slideshow for a homepage is easy. All you need is jQuery.

Steps as follow:

1) Assuming we have 3 images. All these images have same height and width, and positioned absolute. Each of these images are overlapping on top of each other.

<div>
	<img id="home-image-1" class="position-absolute" src="home-image-1.png"/>
	<img id="home-image-2" class="position-absolute" src="home-image-2.png"/>
	<img id="home-image-3" class="position-absolute" src="home-image-3.png"/>
</div>
.position-absolute{
	position: absolute;
}

2) Hide second and third image using jQuery hide(). Now we have only one image showing.

3) Next, we need to make the second image fading in after a certain amount of time in crossfading manner. To do this, we will set first and third images to have z-index = 0 while second image to have z-index = 1.

Note we have second image on top of all other images and it is still hidden. Call fadeIn(‘slow’) for second image.

4) Once fadeIn() animation for second image is completed, call hide() for first and third images.

5) Repeat this method for next images.

To see how to create continues looping of crossfading images, see code sample below:

<script>
	$(document).ready(function(){
		$("#home-image-2, #home-image-3").hide(); //Show first image and hide the rest.
		setInterval(function(){loopHomeImages();},5000);
	});

	var curr = 1;

	function loopHomeImages(){
		var after = (this.curr + 1)%3; //Next image in the loop
		var bef = ((curr - 1) >= 0) ? (curr - 1) : 2; //Previous image in the loop

		$(".position-absolute").css("z-index", 0);
		$("#home-image-" + curr).css("z-index", 1);
		$("#home-image-" + curr).fadeIn("slow", function(){
			$("#home-image-" + after).hide();
			$("#home-image-" + bef).hide();
		});
		curr = (curr + 1)%3;
	}
</script>

That’s all.

Good luck and have fun.

Update Another Drop Down Options Based On Another Using jQuery

Changing a drop down options list based on another selected drop down is easy by using jQuery framework. See demo below:

Demo: http://kennykee.com/demo/dropdown/

Note that there are 2 ways to achieve this. First is to use jQuery framework and jQuery Metadata plugin. Second method is to use HTML5 “data-” attribute. This post will show you the jQuery method.

Explanation of concept
For each <option> tag, we add in metadata. For example

<option class=”option_data {color:’blue,green’}”>Colour Style 1</option>

The data is inserted into the curly bracket next to option_data class. Using jQuery metadata plugin, we can retrieve the “color” variable data. The data will be “blue,green”. Next, we convert this comma separated data into an array by using JavaScript split function. Now, we can create a new drop down with option data using metadata retrieved. We can create new drop down using jQuery. See code example below:

Full Code:

<!DOCTYPE HTML>
<html>
<head>
	<script src="jquery-1.9.1.js" type="text/javascript"></script>
	<script src="jquery.metadata.js" type="text/javascript"></script>
	<style>
		.kennykee-styles{
			font-size: 20px; 
			font-family: Arial; 
			margin: 10px; 
			font-weight:bold;
		}
		#main-style, #result-box select{
			font-size: 50px;
			float: left;
		}
	</style>
	<script type="text/javascript">

		$(document).ready(function(){

			$("#main-style").change(function(){
				$("#main-style option:selected").each(function(){
					var colour_data = $(this).metadata();
					if(colour_data.color){
						var color = colour_data.color;
						var selectObj = $("<select></select>");
						var colorArray = color.split(",");
						for(var i = 0; i < colorArray.length; i++){
							selectObj.append("<option value='" + colorArray[i] + "'>" + colorArray[i] + "</option>");
						}
						$("#result-box").html(selectObj);
						$("#result-box").show("slow");
					}else{
						$("#result-box").hide("slow", function(){
							$("#result-box").html("");
						});
					}
				});				
			});
		});

	</script>
</head>
<body>
	<div class="kennykee-styles"><a href="http://kennykee.com">KennyKee Styles</a></div>
	<select id="main-style">
		<option>--Please Select--</option>
		<option class="option_data {color:'blue,green'}">Colour Style 1</option>
		<option class="option_data {color:'red,white'}">Colour Style 2</option>
	</select>

	<div id="result-box" ></div>

</body>
</html>

Demohttp://kennykee.com/demo/dropdown/

Drawing A Line Between Two Draggable DIVs

Drawing a line between 2 moving DIVs can be tricky sometimes. It involves a little bit of Mathematical knowledge and a few jQuery plugins.

Demo: http://kennykee.com/demo/draw-line/

Drawing A Line Between Two Draggable DIVs

screenshot

The code:

<!DOCTYPE HTML>
<html>
<head>
	<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
	<script src="jquery-ui.js" type="text/javascript"></script>
	<script src="jQueryRotateCompressed.2.2.js" type="text/javascript"></script>
	<style>
		.box{
			width: 100px;
			height: 100px;
			border: solid thin black;
			position: absolute;
			cursor: pointer;
			-webkit-border-radius: 10px;
			-moz-border-radius: 10px;
			border-radius: 10px;
			-webkit-box-shadow:  3px 3px 2px 2px rgba(1, 1, 1, .3);
			box-shadow:  3px 3px 2px 2px rgba(1, 1, 1, .3);
			text-align: center;
			font-weight: bold;
			color: black;
			padding-top: 5px;
			font-family: Verdana;
		}
		.box1{
			background-color: green;
		}
		.box2{
			background-color: yellow;
		}
		#line{
			width: 100px;
			height: 10px;
			border: solid thin red;
			position: absolute;
			background-color: red;
			-webkit-border-radius: 10px;
			-moz-border-radius: 10px;
			border-radius: 10px;
		}
		.kennykee-styles{
			font-size: 20px; 
			font-family: Arial; 
			margin: 10px; 
			font-weight:bold;
		}
	</style>
	<script type="text/javascript">
		var boxCenterXOffset = 50;
		var boxCenterYOffset = 50;

		$(document).ready(function(){
			$(".box").draggable({ delay: 0, distance: 0 },{
				drag: function(event, ui){
					var x1 = $("#box1").offset().left + boxCenterXOffset;
					var x2 = $("#box2").offset().left + boxCenterXOffset;
					var y1 = $("#box1").offset().top + boxCenterYOffset;
					var y2 = $("#box2").offset().top + boxCenterYOffset;

					var hypotenuse = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
					var angle = Math.atan2((y1-y2), (x1-x2)) *  (180/Math.PI);
					if(angle >= 90 && angle < 180){
						y1 = y1 - (y1-y2);
					}
					if(angle > 0 && angle < 90){
						x1 = x1 - (x1-x2);
						y1 = y1 - (y1-y2);
					}
					if(angle <= 0 && angle > -90){
						x1 = x1 - (x1-x2);
					}

					$("#line").queue(function(){
						$(this).offset({top: y1, left: x1});
						$(this).dequeue();
					}).queue(function(){
						$(this).width(hypotenuse);
						$(this).dequeue();
					}).queue(function(){
						$(this).rotate(angle);
						$(this).dequeue();
					});

					$("#gx").html(x1);
					$("#gy").html(y1);
					$("#yx").html(x2);
					$("#yy").html(y2);
					$("#lx").html($("#line").offset().left);
					$("#ly").html($("#line").offset().top);
					$("#degree").html(angle);
				}
			});
		});

	</script>
</head>
<body>
	<div class="kennykee-styles"><a href="http://kennykee.com">KennyKee Styles</a></div>
	<div id="box1" class="box1 box">Drag Me</div>
	<div style="margin-bottom: 100px;"> </div>
	<div id="box2" class="box2 box">Drag Me</div>
	<div style="margin-bottom: 100px;"> </div>
	<div id="line"></div>
	<div style="margin-bottom: 100px;"> </div>

	Green Box: X=<span id="gx"></span> Y=<span id="gy"></span><br />
	Yellow Box: X=<span id="yx"></span> Y=<span id="yy"></span><br />
	Line Box: X=<span id="lx"></span> Y=<span id="ly"></span><br />
	Degree = <span id="degree"></span> <br />
</body>
</html>

Some explanation:
1) First, we have 3 divs. 2 divs will be the draggable objects. The 3rd div will be the “line” connecting these 2 divs.

2) During dragging process, the line div is positioned at the center of first draggable object. Note that “center” means offset of first draggable object plus (+) half the width of draggable object.

3) Next, we have to get the distance between the draggable divs by using hypotenuse formula between 2 points. Set the width of the line div as the distance between the 2 draggable divs.

4) Finally, we have to calculate the angle between the two draggable divs. We can get the angle by using arctangent formula. In JavaScript, we can use Math.atan2(). Set the rotation degree of the line div using this angle.

Note that arctangent has a value between 180° and -180º. Hence, we use the method below to shift the line div to correct position.

if(angle >= 90 && angle < 180){
						y1 = y1 - (y1-y2);
}
if(angle > 0 && angle < 90){
						x1 = x1 - (x1-x2);
						y1 = y1 - (y1-y2);
}
if(angle <= 0 && angle > -90){
						x1 = x1 - (x1-x2);
}

And now we have one line drawn between 2 draggable divs.

Demo: http://kennykee.com/demo/draw-line/

HTML5 WebCam With Images Overlapping

This post demonstrates the basic on how to stream webcam from your computer to Opera browser using JavaScript and overlap image on top of the stream.

If you are looking for overlapping some images on top of the real-time stream, then this post is suitable for you.

View demo here. (Please use latest Opera browser only)

Overlap-Image-With-Webcam

The Basic Method

1) Download latest Opera browser. (Unfortunately, I managed to get this demo working in Opera only)

2) Ensure your webcam has been enabled.

3) Create an HTML file with the following. This creates our video display page.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<title>HTML5 WebCam With Images Overlapping</title>
	<meta name="author" content="KennyKee Technologies. Email: kennykee@kennykee.com">
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
	<script type="text/javascript" src="jquery.js"></script>
</head>
<body style="background-color:white; margin:0px;">
	<h1></h1>
	<div id="camera_area">
		<video height="768" autoplay style="z-index: 0"></video>
		<div id="label" style="position: absolute; z-index: 999"><img src="image.png"/></div>	
	</div>

	<script type="text/javascript">
	$(document).ready(function(){
		var video = document.getElementsByTagName('video')[0]; 
		var heading = document.getElementsByTagName('h1')[0];

		if(navigator.getUserMedia) {
			navigator.getUserMedia('video', successCallback, errorCallback);
			function successCallback( stream ) {
				video.src = stream;
			}
			function errorCallback( error ) {
				heading.textContent = "An error occurred: [CODE " + error.code + "]";
			}
		} else {
			heading.textContent = "Native web camera streaming is not supported in this browser! Please use Opera.";
		}

		//For animation purpose
		$('#label').css({left:'200', top:'200'});
		var next = false;
		var animateMe = function(targetElement, speed){
		var left = 800;
		if(next){ left = 200; next = false}else{next = true;}

		$(targetElement).animate(
				{
				'left': left
				},
				{
				duration: speed,
				complete: function(){
					animateMe(this, speed);
					}
				}
			);
		};
		animateMe($('#label'), 1000);

	});
	</script>
</body>
</html>

Download latest jQuery library and rename as jquery.js. Put this file in the same directory as the HTML file created earlier. Use this image sample. Save as image.png and put in the same directory as the HTML created earlier image.

4) Open the created HTML file with Opera. Make sure you enable webcam request access from Opera.

We are done. View demo here. (Please use latest Opera browser only)