Posts Tagged JavaScript

Initialize LightBox using JSON string and Run it from Flash

Lightbox is the most popular way of showing large image on click on thumbnail over the web. Lot of websites are using the LightBox. Normally, We use lightbox using the “rel” attribute of anchor tag. We use lightbox this way:-

<a href="images/image-1.jpg" rel="lightbox" title="thumb"><img src="images/thumb-1.jpg" width="100" height="40" alt="" /></a>

Here, we provided the “rel” attribute as “lightbox” in hyperlink. What lightbox script do is when page load completed its check all the hyperlinks of page and if rel=”lightbox” is exists them it push this link into an array.
Lightbox extract the “href” and “title” attributes of each link having rel=”lightbox” and push all of them into array. “href” is normally the URL of larger image. Lingtbox also add “click” event on all of these hyperlinks and when user click on any particular thumbnail the lightbox starts.

Here, I’m showing a way in which you can initialize the lightbox by using the JSON string. Basically, this JSON string contains the “href” and “title” information which we want to show. We can create this string dynamically using any server side scripting language. Here is one of sample JSON string.

<script language="javascript">
	var img_json = [['pics/photo-80.jpg', 'Title 01'],['pics/photo-128.jpg', 'Title 02'],['pics/photo-160.jpg', 'Title 03'],['pics/photo-165.jpg', 'Title 04'],['pics/photo-205.jpg', 'Title 05'],['pics/photo-206.jpg', 'Title 06']];
</script>

You can learn more about JSON here.

We also need to do some small changes in lightbox javascript file so it use our JSON string for image array instead of create array by checking the “rel” attribute in whole page.

You can download the customized lightbox javascript file from here.

You can see the working demo here.

1. Remove the “imageLink” parameter from start function because now we not starting LightBox by not clicking any thumbnail.

start: function(imageLink)

function to

start: function()

2. Now we are initializing the “imageArray” using JSON string.

this.imageArray = [];

to

this.imageArray = img_json;

3. Comment these line of code inside start function bacause we not want to check whole page links for lightbox.

/*if ((imageLink.rel == 'lightbox')){
           // if image is NOT part of a set, add single image to imageArray
           this.imageArray.push([imageLink.href, imageLink.title]);         
  } else {
            // if image is part of a set..
            this.imageArray = 
                $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
                collect(function(anchor){ return [anchor.href, anchor.title]; }).
                uniq();
 
            while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
  }*/

4. Add function startLightBox() at the end of Lightbox class. This function start the lightbox when we click on the link having id=”start”.

startLightBox: function() {
	var th = this;
	Event.observe($('start'), 'click', function () {
	 	th.start();
	});
}

5. Add this line in initialize() function to call “startLightBox()” function which create the click event on link having id=”start”.

this.startLightBox();

After completing all the five changes in lightbox.js you need to create a link with id = “start” in your HTML file. When you click on this link its starts the LightBox. Here is the code for HTML file.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Initialize LightBox using JSON string and Run it from Flash</title>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<script src="js/prototype.js" type="text/javascript"></script>
<script src="js/scriptaculous.js?load=effects,builder" type="text/javascript"></script>
<script src="js/lightbox.js" type="text/javascript"></script>
</head>
<body>
<a href="#" id="start">Start LightBox</a>
</body>
<script language="javascript">
	var img_json = [['pics/photo-80.jpg', 'Title 01'],['pics/photo-128.jpg', 'Title 02'],['pics/photo-160.jpg', 'Title 03'],['pics/photo-165.jpg', 'Title 04'],['pics/photo-205.jpg', 'Title 05'],['pics/photo-206.jpg', 'Title 06']];
</script>
</html>

, , , ,

1 Comment


Unscape HTML in JavaScript

This function strips tags and converts the entity forms of special HTML characters to their normal form. I created this function with the help of code of Prototype JavaScript library.

<script language="javascript">
function unscapeHTML(str) {
	var div = document.createElement('div');
    div.innerHTML = str.replace(/<\/?[^>]+>/gi, '');
 
	if (div.childNodes[0]) {
		if (div.childNodes.length > 1) {
			var retStr;
 
			for (var i = 0; i < div.childNodes.length; i++) {
				retStr += div.childNodes[i].nodeValue;
			}
 
			return retStr;
		}
		else {
			return div.childNodes[0].nodeValue;
		}
	}
	else {
		return '';
	}
}
</script>

How you can use it.

<script language="javascript">
var1 = 'x &gt; 10';
alert(unscapeHTML(var1));
// This will alert 'x > 10' 
 
var2 = '<h1>Pride &amp; Prejudice</h1>';
alert(unscapeHTML(var2));
// This will alert 'Pride & Prejudice'
</script>

,

No Comments


Show image when its completely received by browser

Click on Image to see demo

Click on Image to see demo

See demo here

In this example, I am showing how to display image when its completely received by browser. We need this kind of thing when we are changing any Image through JavaScript and want to show some loader until image is not completely receive by client browser. I am using Image onload event for this purpose. Its fires when image is load by browser. When user click on prev or next link we hide the image by adding the ‘hide‘ class to ‘<img>‘. So, user will see the loader image which we placed in the background of image container. When browser load the next image we removed the ‘hide‘ class from ‘<img>‘ and changed its ‘src‘ from older image to new image. I am also using jQuery for adding and removing CSS class from HTML Element. Check out the Javascript, CSS and HTML code below.

HTML Code:-

<div class="container">
    <div class="prev"><a id="prev" href="javascript:void(0);">&laquo;Prev</a></div>
    <div class="image-container"><img id="pic" src="img/blank.jpg" class="hide" /></div>
    <div class="next"><a id="next" href="javascript:void(0);">Next&raquo;</a></div>
    <div class="clear-float"></div>
</div>

CSS Code:-

<style type="text/css" media="screen">
* {
	margin:0; padding:0; border:0;
	font-family:Arial, Helvetica, sans-serif;
	font-size:1em; font-weight:normal;
	font-style:normal; text-decoration:none;
	color:#666;
}
.container {
	width:800px;
	margin-left:auto; margin-right:auto;
}
.image-container {
	height:300px; width:400px; border:#333333 thin dashed;
	margin-top:100px;
	background:url(img/indicator2.gif) center no-repeat;
	float:left;
}
.image-container img {	height:300px; width:400px; }
.prev{
	width:50px;
	float:left;
	margin-left:143px;
	margin-top:250px; 
}
.next{
	width:50px;
	float:left;
	margin-top:250px;
	text-align:right; 
}
.clear-float {	clear:both; height:1px;}
.hide {	display:none;}
</style>

JavaScript Code:-

<script type="text/javascript" src="img/jquery.js"></script>
<script language="javascript">
	$(document).ready(function() {
		var index = 0; var path = 'img/';
		var images = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg"];
		var pre_images = new Array();
		var loaded = new Array();
 
		$("#prev").click(function() {
			index--;
			$("#pic").addClass('hide');
			if (index < 0) {index = images.length - 1}
			getImage();
		});	
 
		$("#next").click(function() {
			index++;
			$("#pic").addClass('hide');
			if (index >= images.length) {index = 0}
			getImage();
		});	
 
		function getImage() {
			if (loaded[index] == true) {
				document.getElementById("pic").src = pre_images[index].src;
				$("#pic").removeClass('hide');
			}
			else {
				pre_images[index] = new Image();
				pre_images[index].src = path + images[index];
				pre_images[index].onload = function() { 
					loaded[index] = true;
					document.getElementById("pic").src = pre_images[index].src;
					$("#pic").removeClass('hide');
				}
			}
		}
 
		getImage();
	});
</script>

, ,

1 Comment


Create or Move Google Map Marker Like twittervision.com

Move Google Map like twittervision.com

Move Google Map Marker like twittervision.com



Check out the demo here.

In this example I am showing how we can move marker on Google Map. This example is inspired by twittervision.com. Here we are changing information on Marker and moving it on Google Map using AJAX and JavaScript. We are refreshing the list of available updates from server in a fixed interval.

1. HTML File

<!--index.html-->
<html>
<head>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAMEzhSKcWoYFZdcgJ2yb9VhQfbBedyeTcqIokiCHhEBJKH_N_NRTEMzJanHbfvVY9Llw4oYuILWGf5Q" type="text/javascript"></script>
<script src="prototype.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
<style type="text/css">
.map {
	width: 800px;	height: 400px;	border:#666666 thin dashed;
	padding: 0;	background: #FFFFFF;	margin-right: auto;	margin-bottom: 10px;
	margin-left: auto;
}
#lastStatus {
	font-size:12px;	font-family: verdana, arial, helvetica, sans-serif;
	color:#333;	padding:5px;
}
#infoWindow {
	width:350px; text-align: left;
}
#infoWindow tip {
	float: right;
}
</style>
</head>
<body>
  <div id="map" class="map"></div>
</body>
</html>

2. JavaScript File

//script.js
 
var infos = [];
var loading = false;
var displayCount = 0;
 
function Info (infoArray) {
	var infoVars = [ 'latitude', 'longitude', 'location_name', 'text'];
 
	for (var i = 0; i < infoVars.length; i++) {
		this[infoVars[i]] = infoArray[i];
	}
}
 
 
Info.prototype.lastStatus = function () {
	var myDiv = document.createElement('div');
	myDiv.innerHTML = this.text;
	myDiv.id = "lastStatus";
 
	return myDiv;	
}
 
Info.prototype.infoWindow = function() {
	var myInfoWindow = document.createElement('div');
	myInfoWindow.id = "infoWindow";
	myInfoWindow.appendChild(this.lastStatus());
 
	return myInfoWindow;
}
 
function loadData() {
	if (!loading) {
		new Ajax.Request('updates.php', { 
			method : 'post',
			onCreate : function () { loading = true; },
			onSuccess : function(transport) {addInfos(transport.responseText);},
			onComplete : function () { loading = false; } 
		});
	}
}
 
function showInfos() {
	var currentInfo = infos.pop();
	if ( currentInfo && currentInfo.show ) {
		currentInfo.show();
		displayCount++;
	}
	if (infos.length == 0)
		loadData();
 
	setTimeout("showInfos();", 5000);
}
 
function addInfos(responseText) {
	var newInfos = eval(responseText);
	if (newInfos.length == 0)
		alert("No Infos Available!");
	else {	
		for (i=0; i<newInfos.length; i++) {
			infos.push(new Info(newInfos[i]));
		}
	}
	if (displayCount == 0)
		showInfos();
}
 
var map;
var userMarker;
var marker;
 
var map_icon = addOptionsToIcon(new GIcon(),{iconSize : new GSize(48,48), iconAnchor : new GPoint(18,43), infoWindowAnchor : new GPoint(45,20), image : '/images/icon.png', shadow : '/images/birdshadow.png'});
 
// add options to a GMaps icon
function addOptionsToIcon(icon, options) {
	for(var k in options)	{
		icon[k] = options[k];
	}
	return icon;
}
 
function loadMap () {
	var w = 800; // Width of map container
	map = new GMap2(document.getElementById("map"), {mapTypes: [G_PHYSICAL_MAP] });
	map.setCenter(new GLatLng(39,76), w>700 ? 3 : 2);
	map.addControl(new GSmallMapControl());	
}
 
Info.prototype.show = function () {
	// clear marker
	map.closeInfoWindow();
	if (marker)
		map.removeOverlay(marker);
 
	// show marker with infoWindow
	marker = new GMarker(new GLatLng(this.latitude,this.longitude), { icon : map_icon });
	map.addOverlay(marker);
	map.openInfoWindow(marker.getLatLng(), this.infoWindow(), {noCloseOnClick : true, pixelOffset : new GSize(25,-22) } );
}
 
addEvent(window, 'load', init);
 
function init() {
	if (GBrowserIsCompatible()) {    
		loadMap();
		loadData();
	} else {
		alert("Sorry, your browser isn't compatible with Google Maps!")
	}
}
 
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
   		obj.addEventListener(evType, fn, false); 
   		return true; 
 	} else if (obj.attachEvent){ 
   		var r = obj.attachEvent("on"+evType, fn); 
   		return r; 
 	} else { 
   		return false; 
 	} 
}

3. PHP File

<?php
//updates.php
 
header('Content-Type: text/javascript; charset=utf-8');
$info[] = array(34.1372273,-117.7023255,"Los Angeles, New Orleans", "Manny Pacquaio's two-round demolition of Ricky Hatton has set up the prospect of the biggest money-spinning fight in the history of boxing.");
$info[] = array(52.6449251,-0.6424268,"England near Rutland Water", "Liverpool, with returning captain Steven Gerrard back in the side, were always in control against a disappointing Newcastle -- who have still to collect their first victory under temporary manager Alan Shearer.");
$info[] = array(37.775,-122.418333,"San Francisco", "Dirk Kuyt squared a dangerous ball into the six-yard box and Israeli Benayoun slid home his fourth goal from seven games, as three defenders stood and watched.");
$info[] = array(40.757929,-73.985506,"New York, NY", "That lead was doubled just six minutes later when Gerrard's corner was met with a superb diving header from Dutchman Kuyt, giving Steve Harper no chance in the Newcastle goal.");
$info[] = array(48.751448,-122.472574,"bellingham, wa", "Xabi Alonso hit the crossbar for Liverpool with a curling 30-yarder as Newcastle struggled to get a foot-hold on the game.");
$info[] = array(45.823041,6.197545,"Here.", "Alonso was stretchered off following that tackle and his replacement Lucas Leiva added a third goal in the 88th-minute when heading home Fabio Aurelio's free-kick.");
$info[] = array(39.755092,-104.988123,"Los Angeles", "The result leaves Liverpool three points behind leaders Manchester United, although Alex Ferguson's side have a game in hand.");
$info[] = array(27.800278,-97.396111,"corpus christi", "Meanwhile, Newcastle remain second bottom on 31 points, level with north-east rivals Middlesbrough who they face next weekend in a crucial showdown, with just three matches remaining.");
 
echo json_encode($info);
?>

, ,

5 Comments


Simple Implementation of Javascript Check and Uncheck All Checkboxes

Javascript Check and Uncheck All Checkboxes

Javascript Check and Uncheck All Checkboxes



A simple example of check and uncheck all checkboxes implementation using javascript. We have created a set of checkboxes under a DIV called container. There is a checkbox at the top for check or uncheck all the checkboxes. We have added a function on the click event of top checkbox and when user click it we check its state as checked or unchecked and assign that state to all the other checkboxes.

Check out the demo here.


JavaScript Code:

<script language="javascript" type="text/javascript">
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
   		obj.addEventListener(evType, fn, false); 
   		return true; 
 	} else if (obj.attachEvent){ 
   		var r = obj.attachEvent("on"+evType, fn); 
   		return r; 
 	} else { 
   		return false; 
 	} 
}
 
addEvent(window, 'load', initCheckboxes);
 
function initCheckboxes() {
	addEvent(document.getElementById('all'), 'click', setCheckboxes);
}
 
function setCheckboxes() {
	var cb = document.getElementById('container').getElementsByTagName('input');
 
	for (var i = 0; i < cb.length; i++) {
		cb[i].checked = document.getElementById('all').checked;
	}
}
</script>

HTML Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Check/Uncheck ALL Checkboxes</title>
<style type="text/css">
.container { width:300px}
.odd { background-color: #edf5fa;}
.even { background-color: #fff;}
.all { border-bottom:#666666 thin dashed; margin-bottom:4px;}
</style>
</head>
<body>
    <div class="container">
    	<div class="all"><label><input type="checkbox" name="cb" value="1" id="all" />Check All</label> </div>
    </div>
    <div class="container" id="container">
    	<div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Elephant</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Lion</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Tiger</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Horse</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Anaconda</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Bear</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Leopard</label> </div>
    </div>
</body>
</html>

,

1 Comment