Posts Tagged jQuery

How know Base Path of Drupal in JavaScript

Sometimes you want to know about the Base Path of your Drupal installation in JavaScript. You may want to know about this path for sending the AJAX request at correct URL relatively, load the image or some other type of file on client side through JavaScript etc.

Drupal provide a variable called Drupal.settings.basePath for this purpose in JavaScript. But this variable is only available if you include any custom JavaScript file or JavaScript block in your module. By default Drupal doesn’t include the ‘jquery.js‘ and ‘drupal.js‘ file in generated output. It only add these files if you add your custom JavaScript file or JavaScript block. We can include our custom JavaScript file in Drupal like this:-

drupal_add_js(drupal_get_path('module','my_module'). '/my_module.js');

The my_module.js file should reside in same directory where my_module module exist. This will force Drupal to add jquery.js and drupal.js files in output.

These two files initialize the Base Path variable. In drupal.js file, on top you can see the initialization of setting object in Drupal object. Like this:-

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

Drupal generate some JavaScript code in Script block inside head tag of each page for extending the settings object with the help of jQuery. Like this:-

jQuery.extend(Drupal.settings, { "basePath": "/" });

You can test the Base Path by adding following code in my_module.js file.

$(document).ready(function() {
	alert(Drupal.settings.basePath);
});

This will alert the Base Path for Drupal installation after loading of the page.

, ,

No Comments


Create Simple Carousel using jQuery

Carousel Image

Carousel

You can see the working demo here.

Carousel is a way to present content in the form of slideshow on web page. Here I’m showing how easily you can create a horizontal carousel using jQuery. You can play with the given code and easily create vertical carousel, circular carousel, auto-scrolling carousel etc.

I’m using jQuery for animation. So, you need jQuery JavaScript library for it. You can download latest jQuery JavaScript library from jquery.com.

So, how it work.

Your basic structure of HTML for Carousel should be like this:-

<div id="my_carousel">
   <ul>
    	<li>some content...</li>
        <li>some content...</li>
        <li>some content...</li>
        <li>some content...</li>
        <li>some content...</li>
        <li>some content...</li>
        .....
    </ul>
</div>

What you need to do before applying “my_carousel” ID to your Carousel DIV.

1. Put any HTML content which you want to display in your LI’s.
2. Create CSS for your Carousel DIV.
3. You also need two images, or button to scroll your content in left and right direction.
4. Assign “btnprev” class to your left button or image.
5. Assign “btnnext” class to your right button or image.
6. Assign “my_carousel” ID to you Carousel DIV.

How JavaScript Code work:-

So, when browser load the page JavaScript look for “my_carousel” ID in HTML and apply all the require attributes and events to your DIV, UL, and LI.

Important JavaScript variables and their purpose:-

step – How many LI’s you want to scroll on click of left and right button.
current – Index or Number of left most visible LI in carousel.
maximum – Total number of LI in carousel.
visible – Number of visible LI’s.
speed – Animation speed.
liSize – Width of one LI in pixels.
liSize – Width of one LI in pixels.
carousel_height – Carousel DIV height.
ulSize – Width of UL. You can calculate it like this liSize * maximum.
divSize – Width of CArousel DIV. You can calculate it like this liSize * visible.

Assign require attributes to DIV, UL, and LI.

$('#my_carousel').css("width", divSize+"px").css("height", carousel_height+"px").css("visibility", "visible").css("overflow", "hidden").css("position", "relative"); 
 
$('#my_carousel ul').css("width", ulSize+"px").css("left", -(current * liSize)).css("position", "absolute");

Here we changed the width, height, visibility, overflow, and position of Carousel DIV. The Carousel DIV overflow = hidden property is very important here, through it we are just showing the require(visible) LI’s which we want to show at a time. We just hide the remaining LI’s.

We also changes the width, left and position of UL.

Assign Click event to left and right buttons/images

Left button/image

$('.btnprev').click(function() { 
	if(current - step < 0 || current - step > maximum - visible) {return; }
	else {
		current = current - step;
		$('#my_carousel ul').animate({left: -(liSize * current)}, speed, null);
	}
	return false;
});

So, we have assigned a click event on previous button. So, we are first checking the index of current LI. If the current LI is the first LI we will not do anything. We will simply return from the function. If the current LI is not the first LI then scroll the content of UL to left hand side by using the jQuery “animate” function. For more information about animate function click here. And we also changed the current to current left most most visible LI.

Right button/image

$('.btnnext').click(function() { 
	if(current + step < 0 || current + step > maximum - visible) {return; }
	else {
		current = current + step;
		$('#my_carousel ul').animate({left: -(liSize * current)}, speed, null);
	}
	return false;
});

Similarly we assigned the clicked event on next button and followed the same logic what we used for previous click. We just changed it slightly to check last LI when we click on next button. If the current is last LI we will do nothing.

Complete JavaScript Code:-

<script language="javascript">
	$(function() {
		var step = 2; 
		var current = 0; 
		var maximum = $('#my_carousel ul li').size(); 
		var visible = 2; 
		var speed = 200; 
		var liSize = 331;
		var carousel_height = 161;
 
 
		var ulSize = liSize * maximum;   
		var divSize = liSize * visible;  
 
		$('#my_carousel ul').css("width", ulSize+"px").css("left", -(current * liSize)).css("position", "absolute");
 
		$('#my_carousel').css("width", divSize+"px").css("height", carousel_height+"px").css("visibility", "visible").css("overflow", "hidden").css("position", "relative"); 
 
		$('.btnnext').click(function() { 
			if(current + step < 0 || current + step > maximum - visible) {return; }
			else {
				current = current + step;
				$('#my_carousel ul').animate({left: -(liSize * current)}, speed, null);
			}
			return false;
		});
 
		$('.btnprev').click(function() { 
			if(current - step < 0 || current - step > maximum - visible) {return; }
			else {
				current = current - step;
				$('#my_carousel ul').animate({left: -(liSize * current)}, speed, null);
			}
			return false;
		});
	});
</script>

, , ,

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


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

,

No Comments