Harness the power of javascript with jQuery

January 20, 2009 05:58 by MatsLycken

What is jQuery, and why should I use it

Quite many .NET developers avoid using client side scripting and often use post backs to do simple updates that could just as well be done on the client. Using a post back where client scripting would have worked just as well is a real bad thing. It makes the web app experience much slower for the end user since the post back needs to send data to the server, it also bogs down the server with unnecessary requests.

Historically javascript has been quite painful to use due to browser differences that forced us developers to use ugly browser sniffing and create duplicate code targeting different vendors.

But things are different today!

jQuery is a small javascript library that makes creating cross browser javascript a breeze. It is an open source frame work that due to it’s simpleness and extensibility has drawn a great following.

Maybe you’re thinking now: “This sounds great, but my project manager would never allow me to use some open source library in my project…” But here’s the thing, Microsoft are officially supporting jQuery and will actually ship it with ASP.NET 4.0!

So convincing your project manager that it’s risk free to include it in your project shouldn’t be too hard. Just look at the ASP.NET demos from PDC ‘08, all of them used jQuery some way or another.

Starting out with jQuery

So now you should go to www.jquery.com and download it. Get the minimized version for production, create a web application in Visual Studio and save the .js file in the web application directory.

We’ll start out with a really simple example, showing and hiding a div.

sample1.htm

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2: <html xmlns="http://www.w3.org/1999/xhtml" >
   3: <head>
   4:     <title>jQuery samples 1</title>
   5:     <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   6:     <style type="text/css">
   7:         .hiddenStuff
   8:         {
   9:             display: none; border: solid 2px #303030; background-color: #ebebeb; padding: 0.5em; width: 200px;
  10:         }
  11:     </style>
  12: </head>
  13: <body>
  14:     <a href="javascript: showIt();">Show it!</a>
  15:     <a href="javascript: hideIt();">Hide it!</a>
  16:     <a href="javascript: toggleIt();">Toggle it!</a>
  17:     <div class="hiddenStuff" style="display: none;">
  18:         This content is hidden!
  19:     </div>
  20:     <script type="text/javascript">
  21:         function showIt() {
  22:             $(".hiddenStuff").show("slow");
  23:         }
  24:         function hideIt() {
  25:             $(".hiddenStuff").hide("slow");
  26:         }
  27:         function toggleIt() {
  28:             $(".hiddenStuff").slideToggle("slow");
  29:         }
  30:     </script>
  31: </body>
  32: </html>

This really simple example contains 3 links that shows, hides or toggles the visibility of the div.

If you take a look at the javascript functions you see how we use jQuery, with $().

If you take a look at the string inside of the parenthesis and the look at the class attribute of the div, you might recognize the string as css selector. This is actually how you make jQuery fetch DOM elements.

Here are some examples how to select DOM elements.

$(“.className”) – selects all DOM elements with the specified css class

$(“#elementId”) – selects the DOM element with that id

$(“tagName”) – selects all DOM elements with that tag

$(“#elementId .className”) – selects all DOM elements with the css class that are descendants of the element with the id

Then you also have a myriad of ways to filter the results to get exactly the elements you want to work with.

When you selector find several elements, the statements you run on the jQuery object will run on all the DOM elements found. You can try and add some more divs with the same class “hiddenStuff” to the sample page. You’ll find that when you click the links all of them will be shown/hidden.

Updating an element

To change the text of an element you use the method text(newText). To retrieve the text contents of an element you use the method with no parameter, text().

sample2.htm

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   2: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3: <html xmlns="http://www.w3.org/1999/xhtml" >
   4: <head>
   5:     <title>jQuery samples 2</title>
   6:     <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   7: </head>
   8: <body>
   9:     <a href="javascript: updateIt();">Click me!</a>
  10:     <span id="update">Waiting for click...</span>
  11:     <script type="text/javascript">
  12:         function updateIt() {
  13:             $("#update").text("The link was clicked! " + new Date().toTimeString());
  14:         }
  15:     </script>
  16: </body>
  17: </html>

Chaning operations

Another great feature that makes jQuery code really small and also (most of the time) easier to read is that is allows chaining of function calls.

Every jQuery method returns a jQuery object. This makes it possible to call another jQuery method on the return value, this is what we call chaining the function calls.

So if we, in the previous sample for instance, would also like to change the appearance of the element when we changed the text would could write:

   1: $("#update")
   2:     .text("The link was clicked! " + new Date().toTimeString())
   3:     .css("background-color", "yellow")
   4:     .css("color", "blue");

 

What this does is really easy to see, it changes the background and foreground color as well as changing the text.

Styling alternate table rows

This is a great example of the power of jQuery.

Often when you have created a table with say a repeater you want to have a different background color of every other row. So naturally you use the AlternateItemTemplate and set a different css class on the tr tag. But then you have to duplicate all the markup in the ItemTemplate, which is not a great thing since now you have to make sure that you update both templates for every change you make.

jQuery makes alternate table styling extremely easy by using the power of selectors.

sample3.htm

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2: <html xmlns="http://www.w3.org/1999/xhtml" >
   3: <head>
   4:     <title>jQuery samples 3</title>
   5:     <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   6: </head>
   7: <body>
   8:     <table>
   9:         <tr><td>the</td><td>brown</td></tr>
  10:         <tr><td>brown</td><td>fox</td></tr>
  11:         <tr><td>jumped</td><td>over</td></tr>
  12:         <tr><td>the</td><td>fence</td></tr>
  13:     </table>
  14:     <script type="text/javascript">
  15:         $("tr:odd td").css("background-color", "#ebebeb");
  16:     </script>
  17: </body>
  18: </html>

As you can see we only need one line of code to style the table

$("tr:odd td").css("background-color", "#ebebeb");

The :odd that comes after the tr selector is a filter. It selects every other element that was found. We then select every td element that was found in every matched row and we change the background color. Nice!

I hope that this has made you interested in jQuery. I can recommend that you go to http://docs.jquery.com for more samples and information about the other methods in jQuery.

Next time I’ll show some examples on how to do event handling in jQuery. Event handling has really been a pain before, but jQuery makes it extremely easy and very powerful.

jQuery samples - part 1.zip (19,42 kb)


Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

October 2. 2009 06:14

An intelligence test sometimes shows a man how smart he would have been not to have taken it

cheap zithromax

October 23. 2009 06:58

Your post is just the same to the thoughts I was having today. Thanks for perfect ideas.

web design

October 29. 2009 03:43

i like

ed hardy shoes

November 27. 2009 01:44

very helpful for developers......

Annuity Reviews

November 29. 2009 12:39

I really liked this brilliant website. Please continue this great work. Regards from John.

fun games

December 3. 2009 14:49

Your post is just the same to the thoughts I was having today. Thanks for perfect ideas.

Cheap auto insurance quotes

December 7. 2009 07:36

i really appreciate this your good article
from there i get something that i want to know
thanks for this usefull informations

free schematic circuit

December 8. 2009 06:29

If you're still on the fence: grab your favorite earphones, head down to a Best Buy and ask to plug them into a Zune then an iPod and see which one sounds better to you, and which interface makes you smile more. Then you'll know which is right for you.

kelsexshop

December 10. 2009 16:09

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

Digital camera

December 11. 2009 13:22

A thoughtful insight and ideas I will use on my blog. You've obviously spent some time on this. Well done!

Fuji Finepix

December 12. 2009 14:14

Hi buddy, your blog's design is simple and clean and i like it. Your blog posts are superb. Please keep them coming. Greets!!!

Bernard Cornwell

December 12. 2009 17:23

Such a wonderful thought. There is nothing else to add other than to acknowledge a job well done. can you show how to grab your rss feed? I couldn't find how.

colon detox

December 13. 2009 18:00

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

Early Learning

December 16. 2009 09:08

<p>I am a working mom in my mid 30-ties from the Southwest, and as a hobby, I run marathons. Therefore, I have to deal with lower back pain quite often. After I did run my last marathon I had to take a time-out. It was aching terribly. Now I am recovering from back pain, because I followed the advice I found here: <a href="www.live-without-back-pain.com/.../" target="_blank">Get Back Pain Relief Now</a></p><p>Thanks again and keep up the authentic work and much success in your business efforts!</p><p>I wish you all a Merry Christmas and a Happy New Year!</p><p>Give A Helping Hand

Have you ever heard of <a href="http://www.changingthepresent.org" target="_blank">changingthepresent.org yet? Changing The Present - Help make the world a better place</a>.</p>

Beverly - Back Pain Relief

December 18. 2009 10:03

This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It’s the old what goes around comes around routine.

guys dating tips

December 18. 2009 18:15

This is getting a bit more subjective, but I much prefer the Zune Marketplace. The interface is colorful, has more flair, and some cool features like 'Mixview' that let you quickly see related albums, songs, or other users related to what you're listening to. Clicking on one of those will center on that item, and another set of "neighbors" will come into view, allowing you to navigate around exploring by similar artists, songs, or users. Speaking of users, the Zune "Social" is also great fun, letting you find others with shared tastes and becoming friends with them. You then can listen to a playlist created based on an amalgamation of what all your friends are listening to, which is also enjoyable. Those concerned with privacy will be relieved to know you can prevent the public from seeing your personal listening habits if you so choose.

baisez

December 18. 2009 22:39

We are a group of volunteers and starting a new initiative in a community. Your blog provided us valuable information to work on.You have done a marvellous job!

Kitchen appliance reviews

December 19. 2009 00:12

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

Quick Salmon Recipes

December 19. 2009 14:55

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

freelance forum

December 20. 2009 03:13

Hey, thanks for that link to <a href="http://www.interpounce.com/toys.php">get the free gift card for toys from Kmart</a>, I tried to use it but its only open to those in U.S.A. which sucks because my mom got hers in 3 days in the mail, but she lives in Denver.

Allyson Whisnant

December 21. 2009 03:59

I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

usa online casinos

December 21. 2009 16:16

This blog post was entertaining. I am looking forward for your next post. Best regards, Jacob Brown ~ pocketpeple

Personalized Gifts

December 22. 2009 19:38

Admiring the time and effort you put into your blog and detailed information you offer! I will bookmark your blog and have my children check up here often. Thumbs up!

Mind Movies

December 23. 2009 09:27

Great advice and tips, Thanks so much!

Annamae Tavenner

December 23. 2009 10:45

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

idaho golf properties

December 23. 2009 14:30

Only want to say your article is astounding. The clarity in your post is simply impressive and i can assume you are an expert on this subject. Well with your permission allow me to grab your rss feed to keep up to date with succeeding post. Thanks a million and please keep up the a uthentic work.

saunders

December 23. 2009 17:39

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

Vania Crafton

December 24. 2009 23:58

Admiring the time and effort you put into your blog and detailed information you offer! I will bookmark your blog and have my children check up here often. Thumbs up!

meilleur taux hypothèques

December 25. 2009 14:53

Hi buddy, your blog's design is simple and clean and i like it. Your blog posts are superb. Please keep them coming. Greets!!!

Antione Piao

December 26. 2009 14:13

good!

exchange rate widget

December 26. 2009 14:14

I like it@!

exchange rate widget

December 26. 2009 14:14

nice !

currency converter widget

December 26. 2009 14:14

thanks!

currency converter widget

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

August 1. 2010 03:18