Archive for category jQuery

Manage (Add, Edit, & Delete) cookies in jQuery

Setting and deleting cookies with jQuery is really easy (especially in comparison to regular JavaScript) but this feature is not included in the jQuery core. For this we need a plug-in. This post shows how to set and get the value of cookies with jQuery.

First download the jQuery cookie plugin for here: http://plugins.jquery.com/project/Cookie

Set a cookie

Setting a cookie with jQuery is as simple as this, here we are creating a cookie called “example” with a value “demo”:

$.cookie("example", "demo");

This is a session cookie and will be destroy when user close his/her browser. To make the same cookie for suppose 7 days. We can do it like this:

$.cookie("example", "demo", { expires: 7 });

The above example will create the cookie at the root level. If you wanted to make it apply only to e.g. “/admin” and make it for 7 days you can do it like this:

$.cookie("example", "demo", { path: '/admin', expires: 7 });

Get the cookie’s value

Getting the cookie’s value is also very easy in jQuery. The following would alert the value of “example” cookie:

alert( $.cookie("example") );

Delete the cookie

And finally, to delete a cookie set its value to null.
Note:- Setting it to e.g. an empty string doesn’t remove it; it just clears the value.

$.cookie("example", null);

,

3 Comments


Getting Browser Information using JQuery

One day every browser will act in same way and support same web standards. However, that’s not today. In a sufficiently complicated web application, it’s important to know which browser user is using so we can know which JavaScript functions are available and which CSS properties it supports. Here, I am showing how you know about the users browser using JQuery. We can find lot of information about users browser like its name, version number etc through jQuery.

At the highest level, JQuery offers an object called browser that contains some simple flags to determine which one of the major browsers is currently being used – Safari, Opera, IE, or Mozilla.

   $(document).ready(function(){
 
    var browser;
    if($.browser.mozilla)
      browser = "Firefox";
    else if($.msie)
      browser = "Internet Explorer";
    else if($.browser.opera)
      browser = "Opera";
    else if($.browser.safari)
      browser = "Safari";
    else
      browser = "Unknown";
 
    $('#browserName').append(browser);
  });

Create a DIV so in your page so you can see the output of this JavaScript.

 <div id="browserName">Your Browser: </div>

When you execute the code, the output should look something like below. If you are using Safari.

Your Browser: Safari

,

1 Comment


How use AJAX in DRUPAL

How use AJAX in DRUPAL

How use AJAX in DRUPAL


We can easily use AJAX in DRUPAL framework. Drupal provide the jQuery javascript library so we can use jQuery for our AJAX implementation. First we write a module in which we are going to implement the server side logic. Suppose our module name is product and we will check the given product name is exist or not in our product table.

<?php
/*product.module*/
 
function product_menu() {
  	$items = array();
 
	$items['product'] = array(
		'page callback' => 'drupal_get_form',
		'page arguments' => array('product'),
    		'access arguments' => TRUE,
    		'type' => MENU_CALLBACK,
  	);
 
  	$items['product/check_name'] = array(
    		'page callback' => 'check_name',
    		'access arguments' => TRUE,
    		'type' => MENU_CALLBACK,
  	);
 
  	return $items;
}
 
function product() {
	$path = drupal_get_path('module', 'product');
	drupal_add_js($path . '/product.js', 'module');
 
	$form['product_name'] = array(
		'#title' => t('Product Name'),
		'#type' => 'textfield',
		'#required' => TRUE,
		'#size' => 30,
		'#description' => t('Please enter product name.'),
	);
 
	$form['check_name'] = array(
		'#type' => 'markup',
		'#value' => "<a href='#' id='check_name'>" . t('Check Product Name') . "</a><br/>",
	); 
 
	$form['status'] = array(
		'#type' => 'markup',
		'#value' => "<span id='status'></span><br/>",
	); 
 
	$form['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
	);
 
	$form['cancel'] = array(
		'#type' => 'markup',
		'#value' => l(t('Cancel'), 'product_mgmt'),
	); 
	return $form;
}
 
function check_name() {
	$name = strtolower($_GET['name']);
 
	$query = "SELECT COUNT(*) AS total FROM {product} WHERE LOWER(product_name) LIKE ('%s')";
	$rs = db_query($query, $name);
 
	$info = db_fetch_object($rs);
	$total = $info->total;
 
	if ($total) {
		echo "$('#status').html('This product is available.');";
	}
	else {
		echo "$('#status').html('This product is not available.');";
	}
}
?>

Don’t return anything in “check_name()” function otherwise it will return the whole page when we access “product/check_name” path through AJAX.

/*product.js*/
 
// JavaScript Document
$(document).ready(function() {
	$('#check_name').attr('href', 'javascript:void(0);');
 
	$('#edit-product-name').keydown(function(event){
		$('#status').html('');
	});
 
    $('#check_name').click(function() {
		var name = $.trim($('#edit-product-name').val());
 
		if (name == '') {
			$('#status').html('Please enter product name.'); return;
		}
 
		$.ajax({
   			type: "GET",
			url: "/product/check_name",
   			data: "name=" + encodeURI(name),
   			success: function(msg){
				eval(msg);
   			}
 		});
	});
});

, ,

16 Comments


A Simple Modal Window Using CSS And JQuery

Simple Modal Window Using CSS and jQuery

Simple Modal Window Using CSS and jQuery


In this tutorial, I’m going to share how to create a simple attractive light weight modal window with jQuery and CSS. I like jQuery, because it makes everything so simple and so easy.

You can view the working demo here.

Right, let’s start, this example will show you how to create a modal window that will display the content of a DIV using its #ID.

For jQuery, please include jQuery file in your page where you want to use this model window.

1. HTML code

# <!-- #dialog is the id of a DIV defined in the code below -->
# <a name="modalwindow" href="#open">Open</a>
#
<div>
#
#     <!--You easily customize your window here -->
#
<div class="window">
#         <strong>Testing of Modal Window</strong> |
#
#         <!-- close button is defined as close window -->
#         <a class="close" href="#">Close window</a>
#
#</div>
#
#     <!-- Do not remove div#hide, because you shall need it to fill the whole screen -->
#
#</div>

2. CSS code

 
# /* Z-index of #hide must lower than #container .window */
# #hide {
#   position:absolute;
#   z-index:9000;
#   background-color:#000;
#   display:none;
# }
#
# #container .window {
#   position:absolute;
#   width:440px;
#   height:200px;
#   display:none;
#   z-index:9999;
#   padding:20px;
# }
#
#
# /* Customize your modal window here, you can add background image too */
# #container #openbox {
#   width:375px;
#   height:203px;
# }

3. Jquery code

# $(document).ready(function() {
#
#     //select all the a tag with name equal to modalwindow
#     $('a[name=modalwindow]').click(function(e) {
#         //Cancel the link behavior
#         e.preventDefault();
#         //Get the A tag
#         var id = $(this).attr('href');
#
#         //Get the screen height and width
#         var hideHeight = $(document).height();
#         var hideWidth = $(window).width();
#
#         //Set heigth and width to hide to fill up the whole screen
#         $('#hide').css({'width':hideWidth,'height':hideHeight});
#
#         //transition effect
#         $('#hide').fadeIn(1000);
#         $('#hide').fadeTo("slow",0.8);
#
#         //Get the window height and width
#         var winH = $(window).height();
#         var winW = $(window).width();
#
#         //Set the popup window to center
#         $(id).css('top',  winH/2-$(id).height()/2);
#         $(id).css('left', winW/2-$(id).width()/2);
#
#         //transition effect
#         $(id).fadeIn(2000);
#
#     });
#
#     //if close button is clicked
#     $('.window .close').click(function (e) {
#         //Cancel the link behavior
#         e.preventDefault();
#         $('#hide, .window').hide();
#     });
#
#     //if hide is clicked
#     $('#hide').click(function () {
#         $(this).hide();
#         $('.window').hide();
#     });
#
# });
#

, ,

6 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