Archive for March, 2010

Choose the Best Website Development Company For Your Website

March 30th, 2010

In this world of internet, website development has become really essential for a company to make their business global. But care should be taken to choose the website as your target audience should find your website attractive and informative.

Posted in Programming Articles | Comments (0)

How to Use the jQuery UI Autocomplete Widget

March 30th, 2010

In this tutorial we’ll be looking at one of jQuery UI 1.8’s newest components – the Autocomplete widget. Auto-completing text fields can be a popular choice with visitors to your site because they make entering information much easier. They can be used on product search fields for example, or when a visitor must enter a country, or a city, or anything else that may be a choice from a common dataset. As well as being popular with visitors, the jQuery UI Autocomplete is popular with developers because it’s easy to use, powerful and flexible.

I’m not a massive fan of Facebook, I much prefer Twitter (@danwellman btw), but one Facebook feature I do like is the messaging feature which lets you send a message to a friend or friends. I like how the autocomplete is used to make selecting your friend’s names easier, and how the names are formatted once they have been selected and added to the ‘to’ field, e.g. they each have a close link in them that allows the name to be easily removed without having to select any text.

In this tutorial we’ll use the jQuery UI Autocomplete widget to replicate this aspect of Facebook’s messaging system. We won’t be looking at actually sending messages however. This is what we’re going to create:


Step 1 Getting Started

We’ll need to build a custom download of jQuery UI containing just the components we need; head over to the download builder at http://jqueryui.com/download. We’ll need to use the following core components:

  • Core
  • Widget
  • Position

We’ll also need the Autocomplete widget itself so ensure that just the above items, as well as Autocomplete, are checked in the Components section at the left. Use the default theme (UI Lightness) and ensure that version 1.8 is selected at the right.

Once downloaded, create a new folder on your computer and call it autocomplete. Then open the archive and copy the css and js folders into the new folder you just created. This will give you all of the library files required for this example including jQuery itself, so this doesn’t need to be downloaded separately.


Step 2 The Underlying HTML

Let’s look at the HTML for the <form> first of all:

<div id="formWrap">
	<form id="messageForm" action="#">
		<fieldset>
			<legend>New message form</legend>
			<span>New Message</span>
			<label id="toLabel">To:</label>
			<div id="friends" class="ui-helper-clearfix">
				<input id="to" type="text">
			</div>
			<label>Subject:</label>
			<input id="subject" name="subject" type="text">
			<label>Message:</label>
			<textarea id="message" name="message" rows="5" cols="50"></textarea>
			<button type="button" id="cancel">Cancel</button>
			<button type="submit" id="send">Send</button>
		</fieldset>
	</form>
</div>

It’s a pretty standard form; there’s an outer container <div> we can use for styling and the <input> that the Autocomplete will be attached to is also within a <div> element; we’ll style the <input> so that it’s slightly hidden, and we’ll style the <div> so that it looks like the other fields in the form. We give the container for the <input> the ui-helper-clearfix class name to make use of this utility class from jQuery UI’s CSS framework.

We’ll also need to link to the files we unpacked from the jQuery UI archive, as well as a custom stylesheet; the following files should go into the <head> of the page:

<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.custom.css">
<link rel="stylesheet" type="text/css" href="css/autocomplete.css">

The following files should go at the end of the <body>:

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.custom.min.js"></script>

Step 3 Styling the Form

We use a very simple, neutral theme in this example, most of which is purely as an example. Very few of the styles are required and most can be changed if necessary. The following CSS is used in the autocomplete.css style sheet (all of the jQuery UI styling is in the jquery-ui-1.8.custom.css style sheet):

#formWrap {
	padding:10px; position:absolute; float:left; background-color:#000;
	background:rgba(0,0,0,.5); -moz-border-radius:10px;
	-webkit-border-radius:10px; border-radius:10px;
}
#messageForm {
 width:326px; border:1px solid #666; background-color:#eee;
}
#messageForm fieldset {
	padding:0; margin:0; position:relative; border:none;
	background-color:#eee;
}
#messageForm legend { visibility:hidden; height:0; }
#messageForm span {
	display:block; width:326px; padding:10px 0; margin:0 0 20px;
	text-indent:20px; background-color:#bbb;
	border-bottom:1px solid #333;	font:18px Georgia, Serif; color:#fff;
}
#friends {
	width:274px; padding:3px 3px 0; margin:0 auto;
	border:1px solid #aaa; background-color:#fff; cursor:text;
}
#messageForm #to {
	width:30px; margin:0 0 2px 0; padding:0 0 3px;
	position:relative; top:0; float:left; border:none;
}
#messageForm input, #messageForm textarea {
	display:block; width:274px; padding:3px; margin:0 auto 20px;
	border:1px solid #aaa;
}
#messageForm label {
	display:block; margin:20px 0 3px; text-indent:22px;
	font:bold 11px Verdana, Sans-serif;	color:#666;
}
#messageForm #toLabel { margin-top:0; }
#messageForm button { float:right; margin:0 0 20px 0; }
#messageForm #cancel { margin-right:20px; }
#friends span {
	display:block; margin:0 3px 3px 0; padding:3px 20px 4px 8px;
	position:relative; float:left; background-color:#eee;
	border:1px solid #333; -moz-border-radius:7px;
	-webkit-border-radius:7px; border-radius:7px; color:#333;
	font:normal 11px Verdana, Sans-serif;
}
#friends span a {
	position:absolute; right:8px; top:2px; color:#666;
	font:bold 12px Verdana, Sans-serif; text-decoration:none;
}
#friends span a:hover { color:#ff0000; }
.ui-menu .ui-menu-item { white-space:nowrap; padding:0 10px 0 0; }

To give the form a nice transparent border with rounded corners we use the CSS3 RGBa rule and the -moz-border-radius, -webkit-border-radius and border-radius rules; most popular browsers now support these rules, including Firefox, Safari, Chrome and Opera. IE doesn’t support either of them, and although it can use a filter to implement rudimentary opacity, rounded corners would need to be supported through the use of images. The effectiveness of the RGBa transparency isn’t shown to its fullest in this example; but this type of form would probably be used as a floating modal overlay in a full implementation, which would sit above actual content on the page.

The container <div> around the <input> field that the Autocomplete text field will be attached to is given the same positioning and styling as the <input> elements, but the <input> within this container has its border removed so that it is hidden. We also reduce its width and float it to the left. This is so that when we add the formatted recipients to the <div> the <input> won’t overflow and increase the height of the <div> unnecessarily.

We also style the recipients, which will be added to the <div> as <span> elements containing a link. Mostly these are styled to match the basic theme and are also given rounded corners. It’s important that these elements are made block-level and also float so that they stack up correctly. We also need to override some of the Automcomplete styling provided by the jQuery UI theme we are using; the last selector simply prevents the individual suggestions in the menu breaking between words, which happens because we have made the <input> it is associated with so small.

At this stage, the form should appear like this:


Step 4 Attaching the Autocomplete

Next we need to attach the Autocomplete widget to the <input> within the <div>; to do this we can use the following script:

<script type="text/javascript">
	$(function(){

		//attach autocomplete
		$("#to").autocomplete({

			//define callback to format results
			source: function(req, add){

				//pass request to server
				$.getJSON("friends.php?callback=?", req, function(data) {

					//create array for response objects
					var suggestions = [];

					//process response
					$.each(data, function(i, val){
					suggestions.push(val.name);
				});

				//pass array to callback
				add(suggestions);
			});
		},

		//define select handler
		select: function(e, ui) {

			//create formatted friend
			var friend = ui.item.value,
				span = $("<span>").text(friend),
				a = $("<a>").addClass("remove").attr({
					href: "javascript:",
					title: "Remove " + friend
				}).text("x").appendTo(span);

				//add friend to friend div
				span.insertBefore("#to");
			},

			//define select handler
			change: function() {

				//prevent 'to' field being updated and correct position
				$("#to").val("").css("top", 2);
			}
		});
	});
</script>

The widget is attached to the <input> using the autocomplete() method. We supply an object literal as an argument to the method, which configures the source option and the select and change event callbacks.

The source option is used to tell the widget where to get the suggestions for the Autocomplete menu from. We use a function as the value of this option, which accepts two arguments; the first is the term entered into the <input>, the second is a callback function which is used to pass the suggestions back to the widget.

Within this function we use jQuery’s getJSON() method to pass the term to a server-side PHP file. The PHP file will use the term to extract matching contact names from a MySql database. We use a JSONP callback to process the data returned from the server; the callback function that is passed as the second argument to the source option expects to receive the data in an array, so we first create an empty array and then use jQuery’s each() method to process each item in the JSON array returned by the server. We simply iterate over each item in this array, and add each suggestion to our new array. Once our new array is built we pass it to the callback function for the widget to display in the menu.

We then define a handler for the Autocomplete’s custom select event; this function will be executed by the widget each time a suggestion is selected from the Autocomplete menu. This function is automatically passed two arguments – the event object and a ui object containing the suggestion that was selected. We use this function to format the recipient name and add it to the <div>. We simply create a <span> element to hold the text and an anchor element that can be used to remove the recipient. Once the formatted recipient has been created we just insert it directly before the camouflaged <input>.

Lastly we add a handler for the change event; this function will be invoked whenever the value of the <input> that the Autocomplete is associated with changes. We just use it to remove the value from the <input> because we’ve already added the formatted version to our container <div>. The carat looks a little high up once a formatted contact name has been added to the <div> so we also use this event handler to correct this.

This is all the configuration we need for this particular implementation, but there are still a couple of additional functions we need to add to tidy things up a little. After the autocomplete() method add the following code:

//add click handler to friends div
$("#friends").click(function(){

	//focus 'to' field
	$("#to").focus();
});

//add live handler for clicks on remove links
$(".remove", document.getElementById("friends")).live("click", function(){

	//remove current friend
	$(this).parent().remove();

	//correct 'to' field position
	if($("#friends span").length === 0) {
		$("#to").css("top", 0);
	}
});

The <input> that our Autocomplete is attached to is partially hidden and its container <div> is styled so that it appears like the other fields on the form; to complete the deception, we add a click handler to the container <div> so that clicking anywhere within it focuses the actual <input>. Visually and functionally now the <div> should be indistinguishable from a regular field.

We also need to handle clicks on the anchor that is added to each formatted recipient; we use jQuery’s live() method because these elements may or may not exist on the page at any given time and it is easier than binding the handler function each time we create one of these anchors. Whenever one of these anchors is clicked all we do is navigate up to the parent of the anchor that was clicked and then remove it from the page. Remember when we corrected the position of the carat earlier in the script? We just need to check whether all the recipients have been removed and if so, reset its position back to its default.


Step 5 Additional Code and Resources

I used a MySql database containing a table listing each of the recipient names, and the following PHP file to accept the data sent by the getJSON() method and pull matching recipients from the database:

<?php

	//connection information
	$host = "localhost";
	$user = "root";
	$password = "your_mysql_password_here";
	$database = "test";
	$param = $_GET["term"];

	//make connection
	$server = mysql_connect($host, $user, $password);
	$connection = mysql_select_db($database, $server);

	//query the database
	$query = mysql_query("SELECT * FROM friends WHERE name REGEXP '^$param'");

	//build array of results
	for ($x = 0, $numrows = mysql_num_rows($query); $x  $row["name"]);
	}

	//echo JSON to page
	$response = $_GET["callback"] . "(" . json_encode($friends) . ")";
	echo $response;

	mysql_close($server);

?>

To run the downloadable example files, you’ll need a development web server with PHP installed and configured, as well as MySql and the appropriate database and table. When a letter is typed into the ‘to’ field, this letter is passed to the server and used to pull out each name that begins with the letter that was typed. The matching names are then passed back to the page as JSON and displayed in the suggestion menu:

This tutorial showed how to replicate Facebook’s message sending form, specifically, the way friends are added to the messaging form as recipients using an Autocomplete, and how the friend names are formatted once they have been added so that they can easily be removed. Our example form doesn’t actually do anything, but what we would need to do to actually send the form would be to pass the contents of the form to a server-side file for sending using AJAX, which could easily be hooked into the submit event of the send button used on the form.

The recipients would need to have some kind of meaning to back-end system of course, and would probably be mapped to email addresses in the database. We’d need to retrieve the textual content of each of the <span> elements before passing back to the server, although this would be a fairly trivial matter.

The jQuery UI Autocomplete widget makes it easy to connect to any datasource and contains a rich suite of event handlers that we can supply functions to in order to react to text being entered into the associated field, or a suggestion being selected from the menu. The widget is styled using jQuery UI’s extensive CSS framework and can easily be changed so that it matches your existing site theme. All in all, it’s an excellent widget that is easy to use and provides great functionality.


Posted in Programming | Comments (0)

E-Shop Helps You for World Wide Internet Marketing Of Your Products

March 28th, 2010

Nowadays internet marketing business has been spread to the world wide and day by day E-commerce business has been spread to the globe. For best e-commerce solutions need best e-commerce websites. So …

Posted in Programming Articles | Comments (0)

What is Website Monitoring Service All About?

March 28th, 2010

A website these days is indispensable to showcase the offerings of your business and to market and sell your products at the same time. So you shell out quite a few dollars to get a slick-looking website and also hire a SEO service to achieve a high rank at the search engines. But it does not end there. You need to keep that position, and it is here that website monitoring service is required.

Posted in Programming Articles | Comments (0)

20 Helpful jQuery Methods you Should be Using

March 28th, 2010

So you’ve been playing with jQuery for a while now, you’re starting to get the hang of it, and you’re really liking it! Are you ready to take your jQuery knowledge to level two? Today, I’ll demonstrate twenty functions and features you probably haven’t seen before!


1 after() / before()

Sometimes you want to insert something into the DOM, but you don’t have any good hooks to do it with; append() or prepend() aren’t going to cut it and you don’t want to add an extra element or id. These two functions might be what you need. They allow you to insert elements into the DOM just before or after another element, so the new element is a sibling of the older one.

$('#child').after($('<p />')).text('This becomes a sibling of #child'));
$('#child').before($('<p />')).text('Same here, but this is go about #child'));

You can also do this if you’re working primarily with the element you want to insert; just use the insertAfter() or insertBefore functions.

$('<p>I\'ll be a sibling of #child</p>').insertAfter($('#child'));

2 change()

The change() method is an event handler, just like click() or hover(). The change event is for textareas, text inputs, and select boxes, and it will fire when the value of the target element is changed; note that this is different from the focusOut() or blur() event handlers, which fire when the element loses focus, whether its value has changed or not.

The change() event is perfect for client-side validation; it’s much better than blur(), because you won’t be re-validating fields if the user doesn’t change the value.

$('input[type=text]').change(function () {
    switch (this.id) {
        /* some validation code here */
    }
});​​​​​​​​​​

3 Context

Context is both a parameter and a property in jQuery. When collecting elements, you can pass in a second parameter to the jQuery function. This parameter, the context, will usually be a DOM element, and it limits the elements returned to item matching your selector that are children of the context element. That might sound a bit confusing, so check out this example:

<p class="hello">Hello World</p>
<div id="wrap">
    <p class="hello">Hello World</p>
</div>
var hi1 = $('.hello'),
    hi2 = $('.hello', $('#wrap').get(0));

console.group('hi1');
console.log("Number of elements in collection:", hi1.length);
console.log("Context of the collection:", hi1.context);
console.groupEnd();
console.group('hi2');
console.log("Number of elements in collection:", hi2.length);
console.log("Context of the collection:", hi2.context);
console.groupEnd();
context example

So where would this be useful? One place might be inside an event handler function. If you’d like to get an element within the one the event was fired on, you could pass this as the context:

$('ul#options li').click(function () {
    $('a', this) . . .
});

4 data() / removeData()

Have you ever wanted to store some bit of information about an element? You can do that easily with the data() method. To set a value, you can pass in two parameters (a key and a value) or just one (an object).

$('#wrap').data('myKey', 'myValue');
$('#container').data({ myOtherKey : 'myOtherValue', year : 2010 });

To get your data back, just call the method with the key of value you want.

$('#container').data('myOtherKey'); //returns 'myOtherValue'
$('#container').data('year'); //returns 2010

To get all the data that corresponds with an element, call data without any parameters; you’ll get an object with all the keys and values you’ve given to that item.
If you want to delete a key/value pair after you’ve added it to an element, just call removeData(), passing in the correct key.

$('#container').removeData('myOtherKey');

5 queue() / dequeue()

The queue() and dequeue() functions deal with animations. A queue is list of animations to be executed on an element; be default, an element’s queue is named ‘fx.’ Let’s set up a scenario:

HTML

<ul>
  <li id="start">Start Animating</li>
  <li id="reset">Stop Animating</li>
  <li id="add">Add to Queue</li>
</ul>
<div style="width:150px; height:150px; background:#ececec;"></div>

JavaScript

$('#start').click(animateBox);

$('#reset').click(function() {
    $('div').queue('fx', []);
});

$('#add').click(function() {
    $('div').queue( function(){
        $(this).animate({ height : '-=25'}, 2000);
        $(this).dequeue();
    });
});

function animateBox() {
  $('div').slideUp(2000)
           .slideDown(2000)
           .hide(2000)
           .show(2000, animateBox);
}

So, here’s what’s going on: in the animateBox function, we’re setting up a queue of animations; notice that the last one calls back to the function, so this will continually repeat the queue. When we click li#start, the function is called and the queue begins. When we click li#reset, the current animation finishes, and then the div stops animating. What we’ve done with jQuery is set the queue named ‘fx’ (remember, the default queue) to an empty array; essentially, we’ve emptied the queue. And what about when we click li#add? First, we’re calling the queue function on the div; this adds the function we pass into it to the end of the queue; since we didn’t specify a queue as the first parameter, ‘fx’ is used. In that function, we animate the div, and then call dequeue() on the div, which removes this function from the queue and continues the queue; the queue will continue repeating, but this function will not be part of it.


6 delay()

When you’re queuing up a chain of animations, you can use the delay() method to pause the animation for a length of time; pass that time as a parameter in milliseconds.

$('div').hide().delay(2000).show(); // div will stay hidden for 2 seconds before showing.

7 bind(), unbind(), live(), and die()

Did you know that when you add a click event to an element like this . . .

$('#el').click(function () { /*******/ });

. . . you’re really just using a wrapper for the bind() method? To use the bind() method itself, you can pass the event type as the first parameter and then the function as the second.

If you use a lot of events, you can categorize them with namespacing; just add a period after the event name and add your namespace.

$('#el').bind('click', function () { /*******/ });
$('#el').bind('click.toolbarEvents', function () { /*******/ }); // namespaced

You can also assign the same function to multiple events at the same time, by separating them with spaces. So if you wanted to make a hover effect, you could start this way:

$('#el').bind('mouseover mouseout', function () { /*******/ });

You can also pass data to the function if you’d like, by adding a third parameter (in the second position).

$('#el').bind('click', { status : 'user-ready' }, function () {
    switch(event.data.status) {
    /********/
    }
});

Sooner or later, you’ll find yourself inserting element into the DOM via an event handler; however, you’ll find that the event handlers you’ve made with bind (or its wrappers) don’t work for inserted elements. In cases like this, you’ll need to use the live() (or delegate) method; this will add the event handlers to the appropriate inserted elements.

$('.toggle').live(function () {
    /* code */
    $('<span class="toggle">Enable Beta Features</span>').appendTo($('#optionsPanel'));
    /* more code */
});

To remove event handlers created with bind(), use the unbind() method. If you don’t pass it any parameters, it will remove all the handlers; you can pass in the event type to only remove event handlers of that type; to remove events from a specific namespace, add the namespace, or use it alone. If you just want to remove a certain function, pass its name along as the second parameter.

$('button').unbind(); // removes all
$('button').unbind('click'); // removes all clicks
$('button').unbind('.toolbarEvents'); // removes all events from the toolbarEvents namespace
$('button').unbind('click.toolbarEvents'); // removes all clicks from the toolbarEvents namespace
$('button').unbind('click', myFunction); // removes that one handler

Note that you can bind/unbind functions you’ve passed in anonymously; this only works with the functions name.
If you’re trying to unbind an event from inside the function called by the event, just pass unbind() the event object.

$('p').bind('click', function (event) {
    $('p').unbind(event);
} );

You can’t use unbind() for live events; instead, use the die(). Without parameters, it will remove all live events from the element collection; you can also pass it just the event type, of the event type and the function.

$('span').die(); // removes all
$('span').die('mouseover'); // removes all mouseovers
$('span').die('mouseover', fn); // remove that one handler

And now, you can wield jQuery events with deftness and power!

You should also review the delegate() method, as there can be substantial performance benefits to using it over live().


8 eq()

If you’re looking for a specific element within a set of elements, you can pass the index of the element to the eq() method and get a single jQuery element. Pass in a negative index to count back from the end of the set.

var ps = $('p');
console.log(ps.length); // logs 3;
ps.eq(1).addClass('emphasis'); // just adds the class to the second item (index in zero-based)

You can also use :eq() in your selectors; so the previous example could have been done like this:

$('p:eq(1)').addClass('emphasis');

9 get()

When getting a collection of element, jQuery returns them as a jQuery object, so you have access to all the methods. If you just want the raw DOM elements, you can use the get() method.

You can specify an index to get only one element.

alert( $('p') ); // [object Object] - the jquery object
alert( $('p').get(1) ); // [object HTMLParagraphElement]

10 grep()

If you’re not familiar with Unix/Linix shells, you might not have heard the term grep. In a terminal, it’s a text search utility; but here in jQuery, we use it to filter an array of elements. It’s not a method of a jQuery collection; you pass in the array as the first parameter and the filtering function as the second parameter. That filter function takes two parameters itself: an element from the array and its index. That filter function should perform its work and return a true or false value. Be default, all the items that return true will be kept. You can add a third parameter, a boolean, to invert the results and kept the items that return false.

Jeffrey Way did a great quick tip about the $.grep not long ago; check that out to see how to use it!

var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');

nums = $.grep(nums, function(num, index) {
  // num = the current value for the item in the array
  // index = the index of the item in the array
  return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

11 Pseudo-Selectors

Sizzle, the CSS Selector engine inside jQuery, offers quite a few pseudo-selectors to make the job of selecting the elements you want easy. Check out these interesting ones:

$(':animated'); // returns all elements currently animating
$(':contains(me)'); // returns all elements with the text 'me'
$(':empty'); // returns all elements with no child nodes or text
$(':parent'); // returns all elements with child nodes or text
$('li:even'); // returns all even-index elements (in this case, <li>s)
$('li:odd'); // can you guess?
$(':header'); // returns all h1 - h6s.
$('li:gt(4)'); // returns all elements with an (zero-based) index greater than the given number
$('li:lt(4)'); // returns all element with an index less than the given number
$(':only-child'); // returns all . . . well, it should be obvious

There are more, of course, but these are the unique ones.


12 isArray() / isEmptyObject() / isFunction() / isPlainObject()

Sometimes you want to make sure the parameter that was passed to a function was the corrent type; these functions make it easy to do. The first three are pretty self explanatory:

$.isArray([1, 2, 3]); // returns true
$.isEmptyObject({}); // returns true
$.isFunction(function () { /****/ }); // returns true

The next one isn’t as obvious; isPlainObject() will return true if the parameter passed in was created as an object literal, or with new Object().

function Person(name) {
	this.name = name
	return this;
}
$.isPlainObject({})); // returns true
$.isPlainObject(new Object()); // returns true
$.isPlainObject(new Person()); // returns false

13 makeArray()

When you create a collection of DOM elements with jQuery, you’re returned a jQuery object; in some situations, you might prefer that this be an array or regular DOM elements; the makeArray() function can do just that.

var ps = $('p');
$.isArray(ps); //returns false;
ps = $.makeArray(ps);
$.isArray(ps); // returns true;

14 map()

The map() method is remotely similar to grep(). As you might expect, it takes one parameter, a function. That function can have two parameters: the index of the current element and the element itself. Here’s what happens: the function that you pass in will be run once for each item in the collection; whatever value is returned from that function takes the place of the item it was run for in the collection.

$('ul#nav li a').map(function() {
  return $(this).attr('title');
});  // now the collection is the link titles
// this could be the beginning of a tooltip plugin.

15 parseJSON()

If you’re using $.post or $.get—and in other situations that you work with JSON strings—you’ll find the parseJSON function useful. It’s nice that this function uses the browsers built-in JSON parser if it has one (which will obviously be faster).

$.post('somePage.php', function (data) {
    /*****/
data =  $.parseJSON(data);
    /*****/
});

16 proxy()

If you have a function as a property of an object, and that function uses other properties of the object, you can’t call that function from within other functions and get the right results. I know that was confusing, so let’s look at a quick example:

var person = {
  name : "Andrew",
  meet : function () {
    alert('Hi! My name is ' + this.name);
  }
};
person.meet();
$('#test').click(person.meet);

By itself, person.meet() will alert correctly; but when it’s called by the event handler, it will alert “Hi! My name is undefined.” This is because the function is not being called in the right context. To fix this, we can use the proxy() function:

$('#test').click($.proxy(person.meet, person));
// we could also do $.proxy(person, "meet")

The first parameter of the proxy function is the method to run; the second is the context we should run it in. Alternatively, we can pass the context first, and the method name as a string second. Now you’ll find that the function alerts correctly.

Prefer a video quick tip on $.proxy?


17 replaceAll() / replaceWith()

If you’d like to replace DOM elements with other ones, here’s how to do it. We can call replaceAll() on elements we’ve collected or created, passing in a selector for the elements we’d like to replace. In this example, all elements with the error class will be replaced with the span we’ve created.

$('<span class="fixed">The error has been corrected</span>').replaceAll('.error');

The replaceWith() method just reverses the selectors; find the ones you want to replace first:

$('.error').replaceWith('<span class="fixed">The error has been corrected</span>');

You can also pass these two methods functions that will return elements or HTML strings.


18 serialize() / serializeArray()

The serialize() method is what to use for encoding the values in a form into a string.

HTML

<form>
    <input type="text" name="name" value="John Doe" />
    <input type="text" name="url" value="http://www.example.com" />
</form>

JavaScript

console.log($('form').serialize());​​​ // logs : name=John+Doe&url=http%3A%2F%2Fwww.example.com

You can use serializeArray() to turn the form values into an array of objects instead of a string:

console.log($('form').serializeArray());​​​
// logs : [{ name : 'name', value : 'John Doe'} , { name : 'url', value : 'http://www.example.com' } ]

19 siblings()

You can probably guess what the siblings() method does; it will return a collection of the siblings of the whatever items are in your original collections:

<div> . . . </div>
<p> . . . </p>
<span> . . . </span>
$('p').siblings(); // returns <div>, <span>

20 wrap() / wrapAll() / wrapInner()

These three functions make it easy to wrap elements in other elements. First off, I’ll mention that all three take one parameter: either an element (which is an HTML string, a CSS selctor, a jQuery object, or a DOM element) or a function that returns an element.
The wrap() method wraps each item in the collection with the assigned element:

$('p').wrap('<div class="warning" />'); // all paragraphs are now wrapped in a div.warning

The wrapAll() will wrap one element around all the elements in the collection; this means that the elements in the collection will be moved to a new spot in the DOM; they’ll line up at the place of the first element in the collection and be wrapped there:

HTML, Before:

<p>
    <span> . . . </span>
    <span class="moveMe"> . . . </span>
    <span class="moveMe"> . . . </span>
</p>
<p>
    <span> . . . </span>
    <span class="moveMe"> . . . </span>
    <span class="moveMe"> . . . </span>
</p>

JavaScript

$('.moveMe').wrapAll(document.createElement('div'));

HTML, After:

<p>
    <span> . . . </span>
    <div>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
    </div>
</p>
<p>
    <span> . . . </span>
</p>

Finally, the wrapInner function wraps everything inside each element in the collecting with the given element:

HTML, Before:

<p>
    <span> . . . </span>
    <span> . . . </span>
</p>

JavaScript:

$('p').wrapInner($('<div />'));

HTML, After:

<p>
    <div>
        <span> . . . </span>
        <span> . . . </span>
    </div>
</p>

Conclusion

Well, now you’ve got more than twenty new jQuery features to play with on your next project; have fun with them!


Posted in Programming | Comments (0)

Learn Dreamweaver Fast

March 26th, 2010

Website building begins with Dreamweaver. The quicker you can learn Dreamweaver and master the basics of this powerful tool the quicker you can begin creating websites. The best way to help yourself i…

Posted in Programming Articles | Comments (0)

Common Website Mistakes That Make Visitors Leave Your Website

March 26th, 2010

Your website is important to you and you want visitors, yet traffic seems to avoid your website. Unfortunately there are things that can prevent your website from reaching the full potential it should. Common website mistakes can prevent visitors from visiting your site or staying long enough to learn anything about what your website offers.

Posted in Programming Articles | Comments (0)

CodeIgniter from Scratch: Shopping Cart

March 26th, 2010

Today, we are going to take a look at the Shopping Cart library for CodeIgniter. This useful class allows us to add and remove items to a shopping cart, update them, and calculate prices. I will demonstrate how you can build a simple shopping cart system with the help of this library..


Catch Up


Day 12: Shopping Cart

Final Project


Posted in Programming | Comments (0)

Key Features of Ecommerce Website Development

March 24th, 2010

The whole concept of the ecommerce has become a boon to the SMB companies across the world, which enables them to have greater accessibility to the global markets at a very, very affordable cost. More…

Posted in Programming Articles | Comments (0)

Next Generation Traffic

March 24th, 2010

Web 2.0 changes the whole known scenario of how we see and use the web. It provides the ability to the user to create and manipulate data. Web 2.0 creates a brand new internet.

Posted in Programming Articles | Comments (0)