Thursday, November 25, 2010

Sorting through the holidays

Just wanted to make a quick blog post before I go gorge myself for Thanksgiving. The sort Function is nothing you haven't seen before but important enough that I at least wanted to touch on it. It basially takes an array and goes over the contents and then passes them to your function in pairs. In the event that your function returns 1, the sort function will swap the items and place the second one first. If your function returns -1, then the first item will be first. In the event the function returns 0, sort will not do anything to the items passed from the array.

A word of caution. It is usually best to convert the values to lowercase so that all sorts are case insensitive. This can make your code cleaner and less prone to bugs.

Saturday, November 20, 2010

When we map objects

It is important to note that we are often passing key/value pair objects to jQuery methods. We can often see this when we are passing multple options to a method. FOr example a statement like:


$('div').css({color:'red', padding: '5px'});

Is just a jQuery method (in this case css) that takes key/value mapped pairs. These mapped pairs can be processed even further so that we can use them in functions or widgets.

By mapping objects we can access them by using the period operator (.), which allows us to use the key's associated value. This makes it fairly simple to handle values the same way that we use arrays.

Wednesday, November 17, 2010

Just serialize me

Often when you are building a website you are offering up some type of content. Occasionally, though you need to capture some end user data and one of the tried and true methods of the world wide web is to use forms to do that. Most forms have some type of format similar to this example:

<form name="someForm" action="somePage.asp" method="post">
 <input name="someField" type="text" />
 <input name="aField" type="text" />
 <input type="submit" name="submit" />
</form>

This is just a simple form that submits two fields of text. With a simple javascript variable you can grab all form fields and by using the handy serialize method you can convert all your form data into a query string.

var someJavascriptVariable = $("#someForm").serialize();

If you prefer to use JSON or some similar type of format you an call the serializeArray method. This returns an object containing the key and value pairs of all your form data.

var someJavascriptVariable = $("#someForm").serializeArray();

You can then combine this with the $.post method to submit your data to a database.

$.post(this.someURL, someJavascriptVariable, function() { alert("submitted!"); });

I added a callback at the end that gives is a pop-up message letting us know that the form has been submitted.

Monday, November 15, 2010

To template or not to template, this is the question

Often when we use some type of AJAX component we are often using the html action to replace part of or all of some elements of the DOM with new elements. Now you can code it for each piece of content in your page or you can take advantage of populating your elements with data when you need it. For example lets suppose we have a next week calculator.

<div id="calculator">
 <p>Next week will be <span id="numDays">0</span> number of days from beginning of the moth</p>
</div>

now with the following jQuerywe can update the text of these containers:

$(this).find('#numDays').text(getNumberOfDays());

We have made the part of the HTML page that will change updateable via client-side templating. The rest of the div tag wil not change and only the number of days will change based on when and where the page is rendered. This can be done for each element and allows for us to leave all the markup in the HTML where it belongs and allows for us to use datasources that can be pulled using AJAX or injected directly via a scripting language.

Wednesday, November 10, 2010

the UI Dialog

If you haven't already used the jQuery UI Dialog component, I highly recommend it. It is a completely resizable and modifiable dialog box that can have a variety of transition effects. Let use a simple div tag:

<div id="uiDialog" title="some dialog box">
  <p>Here is some sample dialog text</p>
  <p>Some more dialog text</p>
</div>


then in our javascript we can create a dialog using:

$('#dialog').dialog({
  autoOpen: true,
  height: 300,
  modal: true,
  resizable: false
});

With this simple code you can create a custom dialog box. The contents are just the content of the HTML itself so all normal markup elements like links and images are fair game inside a separate dialog box. It may not seem that special but when you need to display separate content this is a very useful tool.

Monday, October 4, 2010

Interface Components known as Tooltips

These are the message boxes that appear over a control when an end user hovers over one. You have probably already seen tooltips before in many places on the world wide web. For example when you provide a title attribute for a link or an alt attribute for an image you will usually get that hover effect when viewed in most browsers. These tooltips usually give some useful information about what the link is going to do or what the image is doing in the DOM. It's relatively easy in jQuery to customize the tooltips. Let's say that we have a simple link:

<a href="someOtherLink.html" title="I will take you to some other link">Simple Link</a>

This is just a basic link; but with jQuery we can really make this pop.

// this handles when we hover over the element
$('.someText').hover(function(expression)
{ var theText = $(this).attr('title');
   $(this).data('theToolTipText', theText).removeAttr('title');
  
   $('<p class="theToolTip"></p>').text(theText).appendTo('body').fadeIn('fast');

 },  // now address when we hover off the element with a callback
 function()
 { $(this).attr('title', $(this).data('theToolTipText'));
    $('.theToolTip').remove();
  });

We have now created a small pop up message letting us know what the title of this link or paragraph is without relying on the alt attribute or similar. We handle the hover out effect by calling the remove method on the element and just like that the message is gone!

Saturday, October 2, 2010

How an event propagates

Often in the course of developing a piece of code we will need to observe the flow of an event as it goes through the DOM hierarchy. We will have handlers on elements that will catch the event when it is fired from an element. Once this has happened the event gets passed further up the DOM tree, which means that parent elements have a chance to process the event. So for example when you have two divs inside a webpage. One div is inside the other div like:

<div id="firstDiv"> This is an outer div text. <div id="secondDiv"> This is an inner div text. </div> </div>

Now we can add a handler to each div tag. These handlers will simply create an alert letting us know which element was called.

$('div').click(function(){ alert( $(this).attr('id'));  });

So now when we click on the text: This is an outer div text, we get the alert firstDiv. Now the important point is what happens when you click the inner div text: This is an inner div text, which when clicked generates two alerts firstDiv and secondDiv. This is an example of event propagation. You can see the outer div tag only had its alert shown, but the event propagated out of the inner div tag to the outer div tag and had the inner and outer alerts. This is the result of having an event handler associated to the div's parent element. If this outer div was inside another element it would continue to porpagate up the DOM hierarchy until no more parents were available.

Occasionally you don't want an event to propagate past a certain element. In this case a common techinique you will see is just to return false from the event handler, however you can also use the stopPropagation method which as the name describes prevents the event from propagating futher up the DOM heirarchy.

Saturday, September 25, 2010

Displaying images

I've been coding for close to 12 years now and seen a lot of different formats and ways to display images. Usually the old standby is:

<img src="someImage.jpg" />

However, in the last few years I have seen several great examples of image use in Flash and SilverLight, but I like to keep it simple. Those are 3rd party applications and while they are very useful I like to keep everything native to my DOM. That is why I like using a combination of CSS and Javascript. It turns out jQuery has several plugins that help you write just a little bit of JavaScript and paste in a little CSS from the plugin. Usually it is as simple as voila!

At the company I work for we have been reviewing new image tools. One of the one's I really like was the s3Slider plugin for jQuery. However, I ended up recommending the Nivo plugin. You can see an example of it here:

Click to launch example

As you can see there are plenty of tools that all pretty much achieve a similar effect. Making images more accessible and in a "slideshow" type of format.

Wednesday, September 22, 2010

Keeping it clean

I felt like I should blog at least once about making your code look good. Clean code is generally not a topic discussed much, as personal styles vary but I feel that we should at least mention some better practices to use.

1) Use comments.

This generally should go without saying but you would be so surprised how much code I go through everyday that has not been commented or documented. When you practice commenting your code you make it easier to go back and debug for anyone. If you are really that concerned about it adding the size of the file then clean all comments out in your final version and transfer the comments to some type of documentation. Let's review examples of comments in jQuery:

// Use these two slashes to comment out one line at a time
// Or we use /* */ to span multiple lines
/* Like
 * This
 */

2) Use indentations:

Generally people prefer to use tab indents in their code. An example of this would:

var data = {
      id: id,
      name : name
}

However, you can do what I do and just use space indentation:
var moreData =
{ id: id,
  name: name
}

Either way is acceptable, just stay consistent.

3) Use camel case or an underscore:

Or something to make the code readable and identifiable. I know several people that will simple use:

var variable1 = 0;
var variable2 = 0; ... so forth and so on.

A better way to do it is naming the variable something related to what it is doing or storing.

var dayOfTheMonth = 'Monday';
var name_of_my_teacher = 'Judy Watson';


These are just some simple techniques that will save you and others some time by keeping the code clean and easier to understand.

Tuesday, September 21, 2010

Filter and Adding

A handy command to use when you want to eliminate elements that you have selected is filter. This method works very similar to what it sounds like. Lets look at an example:

$('#ravens p').filter(':not(:last)').hide();

In this simple example we are simply hiding all the ravens paragraph tags, but not the last one.

We can also add elements by using the add method. It works fairly similar to filter except in the opposite way. Let's view an example:

$('#cardinals p').add(':not(:first)').show();

This would allow for your selected cardinal paragraph tags to have elements added by showing them, yet not the first paragraph tag.

Of course you can combine the two methods add and filter, to really get a fine tuned selection of elements. This is a great technique to do a lot with a single line of jQuery code.

Sunday, September 12, 2010

Re Size Me

There are several cool jQuery tricks we can use when we resize any element in the DOM or the window itself. For example the resize event can be used to detect when a view is resized:

$(window).resize(function() { alert("You have resized this!"); });

This little bit of code will pop up an alert message letting you know when you have resized your browser window. Applied to a more practical use we can us the resize event to check if the user has modified the width of a webpage past a certain length. If they do, we change the format of the page to accomodate a wider page. We can also put an else in there to remove formatting if we resize the page more narrowly.  An example might look something like this:

$(document.ready(function()
{ accomodateWidth();
   $(window).resize(accomodateWidth);
 });

function accomodateWidth()
{ if($('body').width() > 600)
   { ... code to add page style for greater than 600px width ... }
   else
   { ... code to remove page style for greater than 600px width ... }
}

This allows for a greater flexibility of control over your page that makes end user experiences more flexible based on the size of their document window.

Thursday, September 9, 2010

Chaining it all together

One of the really powerful features of jQuery is chaining several statements together. Instead of re-using the selectors or calling the this keyword you can instead just run multiple jQuery commands all from the same line. It really is easy once you get the hang of it, you are just appending statements onto the end of the previous statement. Lets look at a paragraph tag element that is going to have the show and fadeIn actions chained together:

$('p:selected').show().fadeOut();

In this example our selected paragraph tag shows itself and then fades out. In theory you can chain as many together as you like.

Tuesday, September 7, 2010

Easy Does It

While on the topic of animation there is an important element to consider called easing. This is basically a speeding up or slowing down of the animation, it also can be used to handle the actual control of animation using the two types of easing: linear and swing. As the names imply a linear animation is just a constant rate of motion; like a straight line. On the other hand a swing animation can start off fast, then slow down and then end the animation fast again. Lets look an example of both:

$('#importantMessage').animate({'height' : '-=200px'}, 2000, 'swing');

$('#importantMessage').animate({'height' : '+=200px'}, 2000, 'linear');

In this example we have the swing animation which will appear as a more natural animation while the linear animation will just appear to increase dramatically, then increase slightly, and finally finish the increase in size dramatically.

This is just the basic animation method. I encourage you to visit the jQuery libraries and find other more advanced forms of easing that use more elaborate algorithms to make the easing even more pronounced. For example there are additional jQuery libraries that do easing with an elastic look, or with a bounce, or even in circular motions among many other types of easing.

Sometimes you will notice your animation will be a little "bouncy". In other words it appears that the animation moves around slightly. This may be due to animating an element that is next to a tag with a margin. Typically to prevent this you will want to remove margins from any offending tags.

Friday, September 3, 2010

A brief dialogue on Callback Functions

Often when you are writing jQuery methods you will notice that you can include a special parameter called the callback function. This can be additional code that you can have run after the effect has been run on whatever method you are using. So for example say we are going to toggle a message:

$('#toggledMessage').toggle('fast', function() { alert('The message has just been toggled') } );

Normally we would have just ended with the 'fast' parameter but we included an additional function after it to be run. In this case the callback function is simply going to generate an alert notifying us that the effect has been toggled. This is a simple example, but we could call much more complex function calls in our calback method.

An important point on this is that these callbacks are refered to as anonymous functions because we are simply calling a generic function in this example that generates an alert message and not assigning it a name. This can be typically be used fairly safely as long as we only use it one place. However, a better idea as you get more famliar with jQuery is to pass a function name and define that function elsewhere in your code. It keeps it cleaner but certainly an anonymous function will work in most examples.

Sunday, August 29, 2010

The animate method

Previously in my last blog I discussed simple ways to fade in and out text or simply toggle it. However, you can use an even more powerful method called animate(). This allows you to do even more manipulation of the CSS properties of a DOM element. A sample example of the animate function is:

$('p').animate({ padding: '40px' }, 2000);

In this example the animate function is working on the paragraph tag in the DOM. This will change the padding of the paragraph tags on this page over a period of 2 seconds. The second parameter 2000 is the number of milliseconds to complete the animation, which is the equivalent of 2 seconds.

Another animation example:

$('#notice').animate({ opacity: 'hide' }, 'fast');

This simply hides the notice and does the animation quickly. There are many examples that we could continue to show but they are very similar and the power of what animate can do should convince you to use the method frequently.

Saturday, August 28, 2010

A little animation

When HTML was being developed in the 1990's, I remember using the BLINK tag. It was a great way to make text have a semi-animated effect; with the text alternating between opaque and translucent text. Nowadays with javascript we can make this effect more subtle and much smoother. A simple example of this would be a button that when clicked will change a line of text inside the DOM. The change in this example is a fade similar to the effect of the BLINK tag mentioned previously. We simply use a method fadein or fadeOut. An example code:

$('#buttonThatWillFadeOutText').click( function(){  $('#textThatWillFade').fadeOut();  } );

OR

$('#buttonThatWillFadeTextBackIntoPage').click( function(){ $('#textThatWillFade').fadeIn(); } );

With the top example fading the text out of the page, and the bottom example being a button that when clicked will fade that same text back into the page. In other words, it will become invisible and then visible again. Another similar animation method that is basically another version of the BLINK tag is the toggle() method. An example of this would be through a button to activate its effect on the text:

$('#buttonThatFadesTextBackAndForth').click( function(){ $('#textThatFadesInAndOut').toggle('slow'); } );

The toggle method will take a duration of time to toggle back and forth and in addition you can include a callback function if you want to add something else to this text change.

Thursday, August 26, 2010

The .css() method

One of the coolest methods in jQuery is the .css method. This allows you to get a style property based on the selector. This is convenient because different browsers have different DOM implementations of a property, but the .css() method accounts for the different implementations and produces the same result no matter which term we use. For example:

.css('backgroundColor')

and

.css('background-color')

return the correct value for both regardless of the DOM implementation.

So, that is all good but what can we actually do with it? The example above simply selects the element but by passing an extra parameter we can actually set the property. An example would look like:

.css('background-color', '#FFFFFF')

We can also pass it a function as a parameter which is a function returning the value to set, or if you really want to unleash the power of this method you can simply pass a map (property-value pairs to set). An example of this would look something like this:

.css( {'background-color' : '#FFFFFF', 'color' : '#DDDDDD' } )

Wednesday, August 25, 2010

More selecting in jQuery

In our last post we touched on selectors in jQuery, however we just started scratching the surface. We can select multiple elements in a jQuery statement like the example below:

$('div, h3, p')

This selects every div element, h3 heading, and paragraph tag in the DOM (Document Object Model). This is the same as the selectors we have looked at before except that we are separating them with a comma to select more than one element.

Filters

One of the more subtle tricks to use when using a selector is to use a filter. A filter simply removes certain items by using a colon : followed by the filter name. An example of a filter can be found below:

$('#someId tbody tr:first')

This selects the first table row in the table body with id someId. To illustrate a similar example:

$('#someId tbody tr:last')

This (as you might guess) selects the last table row in the table body with id someId.

Other filters that we can use are :even, :odd, :eq(), and several others....

Tuesday, August 24, 2010

Selecting selectors

Selectors are fairly straightforward in jQuery. Here are what some of the basic selectors look like:

$('p')
$('div')
$('tr')
$('input')

However, these selectors select all the paragraph tags, every div element, table rows, or input boxes on the page. If we want to select a specific paragraph tag or div element we must specify which one using the same methodology that CSS uses by using id and class names. The element's id can be selected by using the hash symbol # like the example below:

$('#pId p')

Which search's the current DOM (Document Object Model) and looks for a paragraph tag containing the id pId. So in this case the above example would select a paragraph tag that looks like this:

<p id="pId">some text here</p>

It is important in your coding to try to make id's unique. In other words, hopefully you will only have one paragraph tag on your page with this id. If you have another id named pId it will still work but you may confuse the two so it is better to name your id's and classes uniquely to avoid naming conflixts.

Just like id's you can select class elements in the DOM by passing a string consisting of a period symbol . like the example below:

$('.someClass') or if you want to me more specific $('table.someClass')

By specifying the element type before the period symbol you are narrowing down your selection to only the element with class "someClass" rather than all elements with class "someClass". Similar to CSS you can add parent container selectors to narrow the selection even further. An example of this would be:

$('div.testClass span')

Which, if you can guess selects all span elements inside of div elements with class "testClass".

Monday, August 23, 2010

Basic jQuery Scripts

The real trick to understanding jQuery is just getting the basics down. One thing that surprised me is how everything goes through a single function. The one function you use is called (drumroll please...) jQuery. This surprised me when I first started using this language. It kind of reminds me how in JAVA, everything descends from OBJECT.

Basically everything that is used within this jQuery function exists within what we call a NAMESPACE. This is a sandbox approach to handling code and makes sure that everybody plays fair and doesn't do things like overriding other people's functions.

Typically when you see a jQuery statement you will simply see the dollar sign: $. This is an alias that we can conveniently use to help shorten the length of our code. You can still use the full jQuery function like the example below:

jQuery('p').html('Basic jQuery statement');

$('p').html('Basic jQuery statement');

are both the same statement. However the later example saves us roughly 5 keystrokes so I prefer to just use the dollar sign $.

BASIC STATEMENT

$('p').html('Basic jQuery statement');

The example above is a basic jQuery statement. It has three components: a selector, action, and parameters. In this example the selector is $('p') which is selecting the paragraph tag <p></p> in the DOM (Document Object Model). The .html is the action which is applied to the element we selected (in this case the paragraph tag). In this example the action .html gets the HTML contents of the first element in the set of matched elements. The last part of the statement are the parameters which in this example is ('Basic jQuery statement'); which tells jQuery how to apply the action.

To summarize,  the statement above applies to the first paragraph tag and includes the text 'Basic jQuery statement' to it. Our example only passes one parameter but we can pass many more if we need to, depending on the type of action we use.

Sunday, August 22, 2010

Google Libraries API

So I have been trying out Google's API libraries and I have to admit it is worth taking a look at. Basically you just need to sign up for an API key through http://code.google.com/ and once you have your own API key you can include at the top of your webpage the following script tag:

<script type="text/javascript" src="http://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>




where INSERT-YOUR-KEY is the API key you get when you sign up. Once you have included this script you can just simply use google.load() like this:

google.load("jquery", "1.3.5");

if you want a specific version. If you just want to use the most recent version you can use something similar to

google.load("jquery", "1.4");

Some of the more popular libraries that are out there are:
Dojo, jQuery, MooTools, script.aculo.us, and YUI.

That's it! It really makes managing the more popular libraries so much easier than having to keep track of the recent version on your server. The only word of caution is to remember that these are case-sensitive so make sure that you pay attention to the case of your text.

Sunday, August 8, 2010

JQuery DOM modeling

Well thank you for coming to visit this blog. My name is Noah McCollam from Indianapolis, Indiana. Mainly I am here to discuss my ramblings on JavaScript and what we can do with it. I am looking forward to explaining some of the curious aspects of writing code in this environment that I have found or noticed from others. I hope that you enjoy it as much as I do. :-)

So for my first blog I figured I would go into my thoughts on the Document Object Model (DOM). It seems to me that this is the container that most medium will go through in the next 10 years. In order to effectively understand what a webpage is requires a very in depth understanding of the DOM. Basically from what I can tell it is a interface that allows intraction with HTML and XML By having an API that allows for PC users to develop pages and sites that can be viewed on non-PC machines and vice versa we have created a true neutral platform that we can develop collaboratively.