Getting Started with jQuery

Recently I started playing around with jQuery and found it to be really cool. I had used Dojo and mootools a bit before trying jQuery and found I really working with jQuery so far. In order to learn how to work with jQuery I’ve been playing around with several small examples and decided to publish some of them. Mostly for my own reference, but hopefully someone else can find them useful as well.

Installing jQuery and jQuery UI

When I first looked at using jQuery I had a hard time getting my head around what it did exactly. I had used dojo and mootools a bit but not a ton so I was still a noob at using any types of Javascript frameworks. I understand whats going on a little better now but wanted to put up a ‘Getting Started with jQuery’ anyway. Mainly for my own reference but also because I remember trying to get going and wish I could have had some more examples to look at.

When I first looked at using jQuery I had a hard time getting my head around what it did exactly. At that point I had used dojo and mootools a bit but not a ton so I was still a noob at using any types of Javascript frameworks. I understand whats going on a little better now but wanted to put up a ‘Getting Started with jQuery’ anyway. Mainly for my own reference but also because I remember trying to get going and wish I could have had some more examples to look at.

What do I need?
One of the first things that needs to be understood is jQuery is broken up into two major installs. The first one, jQuery is all the core stuff you need to start doing things with jQuery like Selectors, Attributes, Traversing and DOM Manipulation. The other is the User Interface widgets, which contains most of the UI Widgets and cool stuff you see like Accordions, Datepicker, Dialogs, Progressbars, Sliders and Tabs.

In other words you don’t have to have the UI stuff in order to use jQuery but many of the components a web developer commonly needs been developed, tested and are ready to be used in the User Interface install. Below are links to both installs.

There are not many choices for the jQuery download, mainly just whether you want the js files compressed or not. The UI download page lets you choose what widgets you want as well as select from a bunch of different css themes. I took the uncompressed version of jQuery and all the defaults for the UI. I will be using the jQuery 1.3.2/jQuery UI 1.7.2 installs as they are the most up to date as I am writing this.

Let’s write the code
Once you have the both the downloads just unpack them where you want them to go and create a new html page in your application. Then point to three external resources within your html document as follows:

So far you code should look something like this:

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Getting Started with jQuery</title>

<link type=”text/css” href=”css/ui-lightness/jquery-ui-1.7.2.custom.css” rel=”stylesheet” />
<script type=”text/javascript” src=”js/jquery-1.3.2.min.js”></script>
<script type=”text/javascript” src=”js/jquery-ui-1.7.2.custom.min.js”></script>

<script type=”text/javascript”>
$(document).ready(
function()
{
//jQuery code goes here…
}
);
</script>

<style type=”text/css”>

</style>
</head>

<body>

</body>
</html>

Next we are going to add some simple code to make sure it all works. Inside the script tags just add the following.

<script type=”text/javascript”>
$(document).ready(
function()
{
$(“#datepicker”).datepicker();
}
);
</script>

Finally, in the body section of the page add this code:

<body>
Date: <input id=”datepicker” type=”text”>
</body>

Refresh your page and you should see a text field. If you click inside of it you will see the datepicker control open up. If you see the datepicker control it means both the jQuery core and jQuery UI widgets are installed and working correctly. You can start adding jQuery code to your site at will!

Using the jQuery Selectors API

Recently I started playing around with jQuery and found it to be really cool. I had used Dojo and mootools a bit before trying jQuery and found I really working with jQuery so far. In order to learn how to work with jQuery I’ve been playing around with several small examples and decided to publish some of them. Mostly for my own reference, but hopefully someone else can find them useful as well.

Going through the jQuery Selectors API I quickly figured out there are a ton of different ways of locating and selecting elements from the web page you are working with. This page is by no means meant to be an exhaustive listing of them but instead just a few of the ones I explored.

Target Specific Elements

Here we are going to use jQuery to target a specific group of elements within our page. Then we will add a css class to those elements, styling them on the fly. To toggle the style off and on I created a couple of links, and use jQuery’s click() method to handle the event.

The code $(‘a#source1Btn1′).click(… uses the selector API to find an anchor tag with id value of ‘source1Btn1′. So our link will look like <a href=”#” id=”source1Btn1″>.

Inside the function passed to the click method is where we actually add and remove the css class ‘colorOn’. Using the jQuery selectors again we find all of the unordered list elements with the id ‘ex1Container’ and add the class using the code

$(‘ul#ex1Container li’).addClass(‘colorOn’);.

Also, it’s worth noting the $e.preventDefault(); is to prevent the browsers default behavior from happening, which in this case is to find an ‘#’ anchor within the page. I put this in here to keep the browser from jumping back up to the top when the links are clicked. To see the whole example the source code is provided below.

  • Item 1
  • Item 2
  • Item 3
	<script>
	$(document).ready(
	  function()
	  {
	    $('a#source1Btn1').click(
	      function($e)
	      {
	      	$e.preventDefault();
	        $('ul#ex1Container li').addClass('colorOn');
	      }
	    );

	    $('a#source1Btn2').click(
	      function($e)
	      {
	      	$e.preventDefault();
	        $('ul#ex1Container li').removeClass('colorOn');
	      }
	    );
	  }
	);
	</script>

	<style>
	  ul#ex1Container
	  {
	    list-style: none;
	    margin: 0px;
		padding: 0px;
	  }

	  ul#ex1Container li
	  {
		padding: 2px 2px 2px 4px;
		margin: 1px;
	  }

	</style>

	<div>List Element</div>
	 <div>
	  <ul id="ex1Container">
	   <li>Item 1</li>
	   <li>Item 2</li>
	   <li>Item 3</li>
	 </ul>
	</div>

//

Filtering a Selection
This example shows how to select different elements through filtering. Filtering makes it easy to select either a single element or many elements very quickly. Just click on the links below the boxes and read the highlighted detail. Here is a snippet of code that draws the seven boxes below, I’m including this to make the example more clear.

<div id="ex2Container">
   <div id="item1">1</div>
   <div id="item2">2</div>
   <div id="item3">3</div>
   <div id="item4">4</div>
   <div id="item5">5</div>
   <div id="item6">6</div>
   <div id="item7">7</div>
</div>
Searching within a Selection with find() – You can get a group of elements back and then search through those results easily using the find() method. The code below will select all of the <div> elements who are contained within the results returned from the $(‘div#ex2Container’) selection.
$(‘div#ex2Container’).find(‘div’).addClass(‘colorOn’);
Selecting specific siblings with nextAll() – Same as ‘nex’ except not just one element is selected but all siblings after the primary selection will be chosen.
$(‘div#item4′).nextAll().addClass(‘colorOn’);
Selecting specific siblings with prevAll() – Same as ‘prev’ except not just one element is selected but all siblings before the primary selection will be chosen.
$(‘div#item4′).prevAll().addClass(‘colorOn’);
Selecting all (‘*’) – This is a quick way to select all the elements on the page in order to do something universally. This code will remove the colorOn class from any element on the page.
$(‘*’).removeClass(‘colorOn’);
<script>
$(document).ready(
 function()
 {
  $('div#ex2Container').find('div').addClass('colorOff');

  $('a#source2Btn0').click(
  function($e)
  {
   $e.preventDefault();
   $('*').removeClass('colorOn');
   $('*').removeClass('focusColor');
   $('div#reset').addClass('focusColor');
  }
  );

  $('a#source2Btn1').click(
  function($e)
  {
   $e.preventDefault();
   $('*').removeClass('colorOn');
   $('div#ex2Container').find('div').addClass('colorOn');
   $('*').removeClass('focusColor');
   $('div#find').addClass('focusColor');
  }
  );

  $('a#source2Btn2').click(
  function($e)
  {
   $e.preventDefault();
   $('*').removeClass('colorOn');
   $('div#item4').next().addClass('colorOn');
   $('*').removeClass('focusColor');
   $('div#next').addClass('focusColor');
  }
  );

  $('a#source2Btn3').click(
  function($e)
  {
   $e.preventDefault();
   $('*').removeClass('colorOn');
   $('div#item4').prev().addClass('colorOn');
   $('*').removeClass('focusColor');
   $('div#prev').addClass('focusColor');
  }
  );

  $('a#source2Btn4').click(
  function($e)
  {
   $e.preventDefault();
   $('*').removeClass('colorOn');
   $('div#item4').nextAll().addClass('colorOn');
   $('*').removeClass('focusColor');
   $('div#nextall').addClass('focusColor');
  }
  );

  $('a#source2Btn5').click(
  function($e)
  {
   $e.preventDefault();
   $('*').removeClass('colorOn');
   $('div#item4').prevAll().addClass('colorOn');
   $('*').removeClass('focusColor');
   $('div#prevall').addClass('focusColor');
  }
  );

  $('a#source2').click(
  function($e)
  {
   $e.preventDefault();
   $('*').removeClass('colorOn');
   $('div#sourceCode2').slideToggle('slow');
  }
  );

  }
);
</script>

<style>
 div#ex2Container div
 {
  list-style: none;
  margin: 14px;
  padding: 8px;
  width: 20px;
  height: 14px;
  float: left;
  font-weight: bold;
  text-align: center;
 }

 .colorOff
 {
  color: #336699;
  border: 1px solid #e4e4e4;
 }

 .colorOn
 {
  background-color: #CCCC99;
  color: #336699;
 }

 .focusColor
 {
  background-color: #f8fafb;
 }

 .detailText
 {
  margin: 12px 0px 12px 0px;
  padding: 10px 0px 10px 0px;
 }
</style>

<div id="ex2Container">
   <div id="item1">1</div>
   <div id="item2">2</div>
   <div id="item3">3</div>
   <div id="item4">4</div>
   <div id="item5">5</div>
   <div id="item6">6</div>
   <div id="item7">7</div>
</div>

//

Selecting a Child – This will select all of the children of the div element with the id of ‘grandparent’.
$(‘div#grandparent’).children().addClass(‘colorOn’);
Selecting a Parent – This will select the parent of the div element with the id of ‘child’.
$(‘div#child’).parent().addClass(‘colorOn’);
Reset – This will select all of the children of the div element with the id of ‘grandparent’.
$(‘div#grandparent’).children().addClass(‘colorOn’);

One reason jQuery is so sexy…

I have just recently started using jQuery in some of my projects both at work and otherwise but today it has occurred to me why I like it so much. I love how jQuery allows us to separate the presentation from the client side logic even further when coding html. I didn’t really pick up on this at first and it seems subtle to me but when doing simple things like handling a onclick event on a anchor tag it really does become apparent how cool it is.

For example when creating a link in your html, you would normally attach an onclick=”" bit inside your anchor tag like this.

<a href=”#” onclick=”javascript:whateverFunction();” >Link</a>

And then you would have a bit of javascript to handle this:

<script>

function whateverFunction()
{
//do some sweet stuff…
}

</script>

But now a days… things are even better with jQuery! Instead of marking up our html all over the place with event this and event that, we can just use the selectors to find what we want on our page and then add events to it independently.

<script>

$(‘a.baseLink’).click(function($e) {
//do some sweet stuff…
});

</script>

This means our anchor tag from before can now be simplified to look like this:

<a href=”http://levimiller.com”>Link</a>

It also means that all the links in our page who use the class ‘baseLink’ will get the same behavior. To me this seems like a huge improvement, especially when you consider what a pain it has been to attach multiple events to one page element when not all events play nicely with each other.

Render HTML with Struts 2 and Tiles

This is such a simple thing but for some reason I really could not get this to work while writing this blog application. I had the back end working, which handled entering in text to be stored in the database but hadn’t really thought about how I was going to display it to the user.

It turns out it is super easy. This blog is built using Struts2 and Tiles so all that needed to happen in order to make the browser parse it the html I just set the encode attribute to either true or false on the Struts tags in the jsp pages.

Here is an example: <s:property escape=”false” value=”content” />

Struts 2 and Spring

I was having a problem a few weeks ago while trying to set up a j2ee application where I had set up some services that were made available via Spring 2.5 and was trying to use them inside a struts 2 action. The problem was I had not used a service locator to manage and locate my java services, but instead was leveraging Spring annotations to do this. And for some reason I could not just throw in the @Autowire annotation inside my Struts action so I had to figure out how to integration Struts2 and Spring.

Looking back it was actually pretty simple and I really like how it works. Just FYI, here is the technology landscape I am in, which should help provide some context as well. Below I will outline the steps I took in order to get it working.

Java 1.6 Hibernate 3 MySql Struts 2 / Tiles 2 Spring 2.5 Flex 3 BlazeDS

1. Point the struts factory to the spring factory. In your Struts 2 controller (struts2.xml) you must tell Struts to use the Spring Factory instead of the default Struts Factory. To do this simply add this line to your struts.xml file.

<constant name=”struts.objectFactory” value=”org.apache.struts2.spring.StrutsSpringObjectFactory” />

2. Include the Struts Spring jar in the classpath. Struts 2 comes with a spring jar that you will need to include from.

3. In your action you should now be able to use the @Autowire annotation to wire up whatever services you have set up.

public class HelloAction extends ActionSupport
{
@Autowired private SomeJavaSercvice someJavaService;

public String execute()
{
someJavaService.doSomeServiceWork();
return SUCCESS;
}

}

The benefit of this is huge. You no longer have to have a service locator that creates a singleton instance of all your services, which means you don’t have to know the service name to use it or do some crazy jndi lookup to find it and then worry about if its the only instance floating around etc. Spring will do it all for you and this small step will allow your actions to have access to all of the services as well.

Also you can just define these services in a base action and they will be available to all the actions that extend the base. Inany case the ‘someJavaService’ will be populated with a instance of the service and ready to use. No more service locator calls in the prepare method or construtors! yay.

Note: Your services must be marked as a service somehow for spring to know what to do with them or you will get a null value for the ‘someJavaService’ value above. There are several ways to do this including defining them in the applicationContext.xml as beans, or marking them up with the @Service or similar annotation but it must be done. I will cover this in more detail in another entry.

Other things this allows you to do is let Spring create your actions, you just have to replace the class paths in your struts.xml document with a bean name and then define that in your applicationContext.xml document. Or you could do constructor injection in your actions instead of using the @Autowired annotation but I didn’t like either one of these ideas very much.

Anyway that is pretty much it.

Cool iPhone Application

A co-worker, Ben Morrise, has created a cool iPhone app. In short, it’s a game where players hide pennies around the world and other people try and find them.

So if you are playing you would enter in the year and mint of the penny you are hiding. Then a title, description (hint) and a photo of the location and save. This becomes available for anyone to look up on the tengreens.com website although the phone will only show pennies within a 100 mile radius.

Overall, it’s pretty cool and I have hidden a few pennies around town so far. I’m thinking it will be cool to hide some when we are on vacation etc.

The app is called “Scavenger”, and is a free download from the Apple store.

© 2010 Levi Miller. All rights reserved.

Powered by Wordpress | Theme by TricksDaddy