All posts tagged jQuery

Improve your jQuery Selectors: 5 Quick Tips

jQuery is a wonderful way to make Javascript usable for everyone. For those not familiar with jQuery, I suggest you load up jquery.com and have a read through. I’ve and few other authors have also written a few jQuery articles on this very site in the past which you might have read. Here are a few that might interest you.
Build Fancy Tabs in JQuery that Fade Text
jQuery – Javascript Made Easy
Tips for jQuery Live Events
jQuery Plugin Tutorial

This post is about going through previously written code and looking at ways we can improve it, both the readability and the efficiency. Mostly these are little snippets of jQuery that perhaps don’t get noticed during a browse through the documents or are rarely useful. So, I’ll shut up and we’ll get started!

1. Don’t Select by Class if Possible.

Native Javascript contains two selectors: getElementById and getElementsbyTagName. You will notice there is no function to select elements by class. jQuery and most libraries do offer this function, and it’s not hard to write your own function to do it. However, due to it not existing natively, any custom function will be slower than using the two native functions above. So if you can avoid it, select elements by ID or by Tag Name over class where ever possible. Sometimes it is unavoidable of course, but if you can avoid it, do.

2. Save Selectors or chain ‘em up

See what’s wrong with this code?

$("div#elem").hide();
$("div#elem").css("width","200");
$("div#elem").show();

Nothing is exactly wrong. However a lot could be improved. Each time $(“div#elem”) appears, jQuery does a search through the DOM for it. In that snippet of code, jQuery has to search three times for the element. Why make it do all the work? Either chain the functions like so:

$("div#elem").hide().css("width","200").show();

Or save the element (also known as caching):

var myElement = $("div#elem");
myElement.hide();
myElement.css("width","200");
myElement.show();

Any element that you know you’re going to be referencing loads, save. However if you’re just using it in one block of code, I’d use chaining.

Caching also applies to the “this” keyword. Consider this loop:

$("div").each(function(i) {
$(this).addClass("myClass");
if($(this).hasClass("newClass") {
$(this).addClass("anotherClass");
}
});

While this might look all cosy, look how many times jQuery has to select the current element using $(this). This loop is much better:

$("div").each(function(i) {
var $this = $(this);
$this.addClass("myClass");
if($this.hasClass("newClass") {
$this.addClass("anotherClass");
}
});

When saving $(this) to a variable, I always name that variable $this, adding the dollar symbol at the beginning. This is because I can’t call a variable “this” as it’s a reserved word.

3. Contextual Information

If you can provide extra information about the location of an element in the DOM, do. For example:

$(".myElem")

Will work fine, however if you can do this:

$("div.myElem")

This tells jQuery that the item with the class “myElem” must be within a div. So jQuery can use getElementsByTagName first to narrow down the search.

If you’ve already cached an element (see Tip 2) then you can actually add it as a second parameter when selecting another element:

$(".myElem", elementYouCachedInAVariable);

This tells jQuery to search for items with a class of “myElem” from within the cached element, again shortening the amount of work jQuery has to do.

4. Avoid Extra Traversing

The most common example of this is as follows:

$("elem").find("p").hide().parent.find("h2").hide();

What happens here is we find paragraphs within an element, hide it, then select those paragraph’s parent again, then find any h2 elements within that element, then hide it. What’s wrong? We start at the parent level, then find paragraphs within it, but then go back up to parent level to find the h2s within the parent. Why not use the siblings function?

$("elem").find("p).hide().siblings("h2").hide()

But this can be even further improved, as the find() function can take multiple selectors:

$("elem").find("p, h2").hide();

Take a look at the original code and what we have now. Much nicer!

5. Make use of andSelf()

Rarely used as much as it should, andSelf() is useful for chaining the previous selection. For example, take code such as this:

$("div").find("p").addClass("myClass").parent().addClass("myClass");

That would seem the only logical way to do things. But no! Check this out:

$("div").find("p").andSelf().addClass("myClass");

Which again, saves us repeating the addClass() function and generally is nicer to look at.

If you have any questions, please leave a comment or grab me on Twitter: @Jack_Franklin.

jQuery 1.4 Released!

The newest version of the popular JavaScript library is now available! The jQuery team has done some great improvements to the already awesome codebase including core optimaztion and rewrites to adding new methods and additional functionality to some of the old ones. Exciting, huh?

The jQuery team is running a promotion for 14 days (starting on the 14th, so now down to 12!) to celebrate the release called “14 Days of jQuery”. They’re going to release something new every day including the newest version of jQuery UI (1.8) on the last day! With this promotion is an every-day chance to win a year of free hosting from media temple and maybe even a 13″ MacBook Pro!

Be sure to check out their 1.4 site (http://jquery14.com) to read and watch about the new improvements!

http://jquery14.com
http://mediatemple.net/jquery14

Introduction to Ajax with jQuery

jQuery is one of the most popular javascript frameworks out there and for good reason. It has a plethora of features that make it a pleasure to work with. One of these is Ajax. Ajax is a way of sending information to the browser and retrieving it without loading the page. So, we can use this when we submit a form, everything happens without the page refreshing. With normal javascript this is nothing short of a nightmare but with jQuery it’s much easier. For this lesson’s purpose I’ve created a simple form that asks the user for their name and password, and will then display it on screen. However, whatever you want to do with the data, the Ajax is exactly the same.

So here is my HTML form, nothing fancy at all:

	<div></div>
	<form method=&quot;post&quot; action=&quot;run.php&quot;>

		<input type=&quot;text&quot; name=&quot;name&quot; value=&quot;Please Enter Your Name&quot;>
		<input type=&quot;text&quot; name=&quot;email&quot; value=&quot;Please Enter your Email&quot;>
		<input type=&quot;submit&quot; value=&quot;Submit&quot; id=&quot;submitbutton&quot;>
	</form>

You’ll notice a small amount of PHP in there which is used to display the user’s name and email. It is important to remember that before we add the jQuery we must make sure the form works without it. The empty div is for displaying the data using jQuery. I’ve also created run.php, which will display the user’s information:

	echo '<h1>';
	echo $_POST['name'];
	echo ', your email is ';
	echo $_POST['email'];
	echo '</h1>';

You could have all of those in one echo statement, but for clarity I’ve split it over multiple lines. If you run it now, you will see when you add your data and click submit it takes you to a new page which shows what you entered. So our form works now, without any jQuery. Now we can look at making it work using Ajax. Hoorah!

The Ajax

So our first step is to include jQuery. I suggest you use Google’s CDN to do this like so:

<script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot; type=&quot;text/javascript&quot; charset=&quot;utf-8&quot;></script>

Select the Button

Now we need to tell jQuery only to run when the DOM Is loaded, and then select our submit button (which, if you check the HTML, I gave an id of “submitbutton” so we could easily select it)

	$(function() {
			$('#submitbutton').click(function(e) {

			});
		});

You might notice that I’m passing a variable ‘e’ in. e represents the event, which in this case will be a mouse click. So the variable ‘e’ contains loads of information about the mouse click and also a nifty function which we will use later.

Setting Up the Ajax

var formData = $('form').serialize();

				$.ajax({
					type: "POST",
					url: "run.php",
					data: formData,
					success: function(d) {

						$('div').empty().html("hi " + d);

					}
				});

There you have all the code that makes up our Ajax request. First we use jQuery’s serialize() function. This gets the data from the form so we can then use it, and so we can use it later we save it to a variable called formData. Once this is done we create a new instance of jQuery’s ajax object and set up various parameters which I shall explain below:

type: "POST", //can be POST or GET, depending on which method you are using
url: "run.php", //relates to the php file we created earlier.
data: formData, //the data we are passing through

Success!

Now we need to create a function to actually display the data. We name this success (it must always be called this) and all we do is select ourdiv, then empty it, before adding the word “hi”, followed by a variable “d”. If you look, you’ll notice I passed in a variable “d” into our success function. This variable stores whatever was returned from the call. So all we then have to do is echo it out.

One last Thing

Remember we passed the variable ‘e’ in at the very beginning? We did this because we need to actually disable the default action for the submit button. If we don’t do this then the submit button will just act like normal and refresh the page and do what it normally does. It’s really easy though, just one line:

e.preventDefault();

And that’s it.

Done!

Here is the entire jQuery code:

$(function() {
			$('#submitbutton').click(function(e) {

				var formData = $('form').serialize();

				$.ajax({
					type: "POST",
					url: "run.php",
					data: formData,
					success: function(d) {
						console.log(d);
						$('div').empty().html("hi " + d);

					}
				});
				e.preventDefault();
			});
		});

Time to test it, load it up, fill it out, click submit and you should see it change without refreshing the page. Voila! We are finished.

Demo