Posts Tagged JavaScript

Round Number upto 2 decimal places in JavaScript

JavaScript’s Math.round() function doesn’t provide facility to round off a number up to 2 or more decimal places. So, here I’m showing a simple JavaScript code using which you can round off numbers up to 2 decimal places. You can change this for more decimal places.

var retailPrice = 9.99;
var percentage = 0.2525; /* 25.25% */
var decimalPlace = 100; /* 100 for 2 decimal place. 1000 for 3 decimal place.*/
 
var wholeSalePrice = Math.round(percentage * retailPrice * decimalPlace) / decimalPlace;
 
alert(wholeSalePrice); /* This will show 2.52 */

2 Comments


JavaScript List Search using jQuery

List Search using jQuery

List Search using jQuery


Here in this example we are using jQuery to filter the list of products. We have list of products in UL and LI. We have associated the “KeyUp” event on the top search textbox. So when somebody type in the textbox we filter the list on the basis of entered value.

We are using the RegExp for comparing the string for matching characters. First we created the regular expression “rg” from the given text and compare the product name (string) with the help of search function.

The search function return the position of string where match is found or ‘-1′ in case of no match.

So, we selected all the LI’s exist inside the ‘product_listID and match each product name one by one. We hide the LI if its text not match the current search text and display the LIs with matching text.

HTML Code: -

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sales Vu</title>
<link rel="stylesheet" href="pm-common-new.css" type="text/css" />
<!--[if IE]><link rel="stylesheet" href="ie.css" type="text/css" media="screen, projection"><![endif]-->
</head>
<body style="padding-left:20px;">
<div class="top-bar">
    <div class="top-left-corner"><img src="images/top-left-corner.png" /></div>
    <div class="top-mid-bg">Product Management</div>
    <div class="top-right-corner"><img src="images/top-right-corner.png" /></div>
</div>
<div class="body-part">
    <div class="body-part-top">
        <div class="search-container">
            <div class="search-box" style="float:left; width:257px;">
                <div style="float: left; width: 70px; padding-top: 4px; font-weight: bold;">Search&nbsp;</div> 
                <div class="text-field-box">
                    <input name="" type="text"  id="search" autocomplete="off" class="search-box-bg" />
                </div>
                <div class="text-field-cancel-button">
                    <a href="javascript:void(0);" id="search_clear" ><img src="images/search-box-cancel.png" border="0" id="search_clear" /></a>
                </div>
            </div>
        </div>
        <div class="modifier-product">
            <div class="modifier-product-right" style="float:left;">
                <div class="modifier-product-right-top">
                    Product
                </div>
                <div class="modifier-product-right-mid">
                    <div class="modifier-product-right-detail" id="product_list">
                        <div class="modifier-product-right-detail-heading">
                            <div class="product-list-heading">Product</div>
                            <div class="price-list-heading">Price ($)</div>
                        </div>
                        <div class="product-list">
                            <ul>
                            	<li>
                                    <div class="product">Banana Split</div>
                                    <div class="price">3.00</div>
                                </li>
                                <li>
                                    <div class="product">Bird Lite</div>
                                    <div class="price">2.45</div>
                                </li>
                                <li>
                                    <div class="product">Butter</div>
                                    <div class="price">2.00</div>
                                </li>
                                <li>
                                    <div class="product">Chicken With Coke</div>
                                    <div class="price">3.45</div>
                                </li>
                                <li>
                                    <div class="product">Chips With Coke</div>
                                    <div class="price">3.75</div>
                                </li>
                                <li>
                                    <div class="product">Corono Lite</div>
                                    <div class="price">2.00</div>
                                </li>
                                <li>
                                    <div class="product">Eggs</div>
                                    <div class="price">0.50</div>
                                </li>
                                <li>
                                    <div class="product">Limca</div>
                                    <div class="price">1.05</div>
                                </li>
                                <li>
                                    <div class="product">Sprite</div>
                                    <div class="price">1.20</div>
                                </li>
                                <li>
                                    <div class="product">test product</div>
                                    <div class="price">3.00</div>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="modifier-product-right-bottom">
                    &nbsp;
                </div>
            </div>
        </div>
    </div>
    <div class="body-part-bottom">
        <img src="images/body-bottom.png" />
    </div>
    </div>
</body>
</html>
<script src="jquery.js" type="text/javascript"></script>
<script src="pm_new.js" type="text/javascript"></script>

JavaScript Code: -

// JavaScript Document
$(document).ready(function () {
	$('#search').keyup(function(event) {
		var search_text = $('#search').val();
		var rg = new RegExp(search_text,'i');
		$('#product_list .product-list .product').each(function(){
 			if($.trim($(this).html()).search(rg) == -1) {
				$(this).parent().css('display', 'none');
 				$(this).css('display', 'none');
				$(this).next().css('display', 'none');
				$(this).next().next().css('display', 'none');
			}	
			else {
				$(this).parent().css('display', '');
				$(this).css('display', '');
				$(this).next().css('display', '');
				$(this).next().next().css('display', '');
			}
		});
	});
});
 
$('#search_clear').click(function() {
	$('#search').val('');	
 
	$('#product_list .product-list .product').each(function(){
		$(this).parent().css('display', '');
		$(this).css('display', '');
		$(this).next().css('display', '');
		$(this).next().next().css('display', '');
	});
});

, ,

1 Comment


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>

, , , ,

No Comments


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