Difference between revisions of "Introduction to JavaScript Fall 2010 Class 5"

esse quam videri
Jump to: navigation, search
m
m
 
Line 30: Line 30:
  
 
=== Selectors ===
 
=== Selectors ===
 +
 +
While CSS styles are important, you will first need to understand CSS selectors before you can use jQuery. Below are three different types of
 +
selectors that you will commonly see used with jQuery.
  
 
'''Tag'''
 
'''Tag'''

Latest revision as of 22:12, 5 October 2010

Back to Introduction to JavaScript Fall 2010

Introduction

So far, we've been writing all of our JavaScript by hand. You may have noticed that some if it gets repetitive. Typing document.getElementById and giving all of the elements on your page ids might start to seem like a chore. Thankfully, there are ways to streamline the process of adding JavaScript to your page.

One thing that you can do to speed up your JavaScript development is use a JavaScript library. JavaScript libraries are collections of handy functions and tools that have been written by other people. When you include a JavaScript library on your page you can take advantage of the functionality that other people have written.

In this class, we will be mainly focusing on a library called jQuery. jQuery is an open source library that provides utlities for adding JavaScript event handlers to page elements and for manipulating HTML elements using JavaScript.

A Word About CSS

One important element that you will need to understand before using jQuery is Cascading Style Sheets (CSS). If you don't already know how to use CSS, here is a brief summary of the basic elements of CSS.

As I have mentioned before in this class, CSS is used for styling the HTML elements of your page. CSS consists of selectors, which are used to target HTML elements on the page, and styles, which are used to style the elements that are being targeted.

For example, the following piece of code targets elements that have the class name .callout, and gives them a blue border that is 3 pixels thick:

 .callout {
   border: 3px solid blue;
 }

Selectors

While CSS styles are important, you will first need to understand CSS selectors before you can use jQuery. Below are three different types of selectors that you will commonly see used with jQuery.

Tag

Tag selectors select a type of HTML tag. Each selector matches up with the name of the HTML tag you'd like to target. The following CSS targets all h3 tags and makes the text inside of them red:

 h3 {
   color: red;
 }

ID

ID selectors are used to target elements that have a particular ID. ID selectors consist of a pound sign (#) and the ID you'd like to target. ID's should be only used one time per page, so an ID selector will target a single item on the page. For example, you could target the element with an ID of "logo" like this:

 #logo {
   float: left;
   border: 1px solid blue;
 }

Class

Class selectors select all HTML tags of a particular class name. Class selectors consist of a dot (.) followed by the class name you'd like to target. So, for example, a CSS rule that targets all elements with a class name of "selected" looks like this:

 .selected {
   background: yellow;
 }

Combining Selectors

Often, you will need to combine several selectors to target the right elements. CSS selectors can be chained together in many ways. I won't outline them all here, but here are a few ways they can be chained.

More Specific Selectors

Sometimes, you might want to only target HTML tags that are of a certain class. You can target tags that have a certain class by listing the tag, immediately folowed by the class name, with no spaces. For example, only target list items with the "selected" class.

 li.selected {
   background: yellow;
 }

Child Elements

You can also target elements that are children of other elements. If you list a CSS selector followed by a space and then another CSS selector, the second selector must be a child element of the first selector. For example, only target li items that are inside of the element with an ID of "nav":

 #nav li {
   border: 1px solid green;
 }

Multiple Classes

If you'd like to target elements that have multiple classes on them, you can chain classes together by listing them one after another, with no spaces. The following CSS selector will target elements that have both the "disabled" and the "broken" class on them:

 .disabled.broken {
   color: red;
   background: gray;
 }

Complex Selectors

CSS selectors can be as simple or as complex as you want. This selector will target list items with a class "todo" that are inside of a paragraph tag, inside of the element with an id of "content":

 #content p li.todo {
   color: yellow;
 }

There are many other ways to target elements with CSS. This has just been a very basic introduction. If you'd like to read more about CSS, W3Schools has a good introductory tutorial here.


jQuery

jQuery offers more functionality than I can cover in one class. This week I'll start out with some basic functionality that will get you started with using the library.

Including jQuery (or Other Libraries)

Before you can start using jQuery, or any other library that you want to use with your page, you will need to include the library code. There are two options for including the jQuery code. The first option is to download the code for the library and include it with the rest of your project. The second option is to include a reference to a hosted version of jQuery.

Option 1: Download jQuery Locally

The jQuery library can be downloaded from the jQuery homepage. Once you've downloaded the code and saved it to a file called jQuery.js (or whatever named makes the most sense to you), you can include the code on your page, just like you've been including the code so far.

Say you downloaded the file, named it jQuery.js and stored it in your javascripts folder. To include it on your page, you'd simple add the following line to your code:

  <script src="javascript/jQuery.js" type="text/javascript"></script>

Make sure the script is included on your page before any of the scripts that take advantage of jQuery. Otherwise, your scripts won't be able to find jQuery and won't work.

The downside to using this option is that you will need to have your own copy of the jQuery code, even though your jQuery code will be exactly the same as it is on other sites.

The upside is that it gives you control over the jQuery code you include and allows you work on your project even without an Internet connection.

Option 2: Use a Hosted jQuery

You can also choose to include a hosted version of the jQuery code. This means that a 3rd party company is hosting the jQuery code for you. Usually the code will be hosted by a well known, and reliable company like Google.

The downside to using this option is that it may take your page slightly longer to load while the JavaScript is loading from the 3rd party website. This won't always be an issue, because the code will be cached in the browser after the first time the user loads your site, but it's still an issue to be aware of.

You also have less control over the jQuery code that you're including and you may be in trouble if the 3rd party site is not responding.

The upside is that you won't have to manage the jQuery code as part of your project. Also, if other people are using the same 3rd party hosted jQuery library, the browser will only have to load jQuery the first time it sees a reference to the hosted version.

Selectors with jQuery

One of the best features of jQuery is the ability to find elements on the page using CSS style syntax. So far, we've been finding elements like this:

  var element = document.getElementById("my-element");

This works fine, but it requires that we add ids to all of the elements that need are needed by the JavaScript. If we were using CSS we'd be able to use this syntax to find the element and add styles to it:

  #my-element { border: 1px solid black; }

With CSS we could also find elements by class:

  .with-border { border: 1px solid black }

Or we could even target child elements of other elements:

  ul#border-list li { border: 1px solid black; }

Which lets us find the child elements of certain elements on the page and apply special styles.

With JavaScript, these kinds of selectors take a lot of code to create. I haven't showed you how to do anything like that that yet, and, in reality, the complexities of creating code that worked that way across all browsers would be more than one introductory course could cover. Thankfully, jQuery adds these kinds of selectors to JavaScript already.

Back to finding our element with the id of my-element. With jQuery, we could simply say this:

  var element = $('#my-element');

The $ function is a special function added by jQuery that takes in a CSS style selector and returns all of the elements that were that matched by that selector.

So, if I wanted to find all of the elements that had the class with-border I could make a jQuery call like this:

  var elements = $('.with-border');

Or maybe I wanted to find all of the elements of the unordered list with the id border-list:

  var listItems = $('ul#border-list li');

Notice how similar the selectors are to CSS? The idea is that any valid CSS selector should work with jQuery. So, you no longer have to worry about putting an id on every element of the page or about writing your own functions to figure out which elements should be modified with JavaScript.

See more on jQuery selectors here.

Note: If you look around the web for examples of jQuery being used, you may see some code that uses a function called jQuery, instead of the $ function. With the jQuery library, the jQuery function is exactly the same as the $ function

Events with jQuery

Once you've found an element or a list of elements with jQuery, you can start adding events to it. Events in jQuery work similarly to events in plain old JavaScript. One of the biggest differences, though, is that I can add multiple event handlers to one element. Let's say that I wanted to add a click handler to my-element. I could find it and attach an event with jQuery like this:

  function clickHandler() {
      alert('hi');
  }
  
  var element = $('#my-element');
  element.click(clickHandler);

Notice that, instead of setting onclick equal to clickHandler, we are passing clickHandler into a function called click. The reason that jQuery does it this way is because it allows you to add other handers if you wanted:

 function clickHandler() {
     alert('hi');
 }
 
 function anotherHandler() {
     alert('another');
 }
 
 var element = $('#my-element');
 element.click(clickHandler);
 element.click(anotherHandler);

In the example above there are two handler functions, and I've added them both to element using the click function that jQuery provides.

Another difference between regular JavaScript and jQuery is that the jQuery function doesn't just return one element, it returns all elements that match the selector you passed in. Let's say that you had an unordered list on your page like this:

  <ul id="myList">
     <li>Item</li>
     <li>Item</li>
     <li>Item</li>
  </ul>

The list has 3 items and you'd like each item to call a handler when the user mouses over the item. jQuery allows you to select all of the items and attach and event to all of them at once:

  var listItems = $('#myList li');
  listItems.mouseOver(handlerFunction);

The selector #myList li finds all of the list items inside of the element with an id of myList. jQuery returns a collection of all of the list items. You can then add the event handlers the same way you'd add them to an individual item. In this case, the mouseOver function takes in a handler function that will be called whenever the user puts their mouse over any of the list items.

One other thing to note: just like when you attach an event handler to an event with regular JavaScript, event handlers attached with jQuery refer back to the element that the handler is tied to by using the this keyword (as you'll see below).

See more on jQuery events here

Changing Styles with jQuery

jQuery also has some tricks for changing the styling of elements. Above, we attached an event handler to all of the elements in this list:

  <ul id="myList">
     <li>Item</li>
     <li>Item</li>
     <li>Item</li>
  </ul>

Instead of attaching a generic eventHandler function, let's create a function called changeStyle that will change the style of each list item when it's clicked on. Attaching the event handler is simple:

  var listItems = jQuery('#myList li');
  listItems.click(changeStyle);

Now, we need to create a function called changeStyle. First, let's use the jQuery css function to directly modify the CSS styles of each list item:

  function changeStyle()
  {
      var element = jQuery(this);
      element.css({ background: "blue", border: "5px solid black"});
  }

There are a couple things going on with this function. First, we're passing this to the jQuery function. In this case, think of jQuery as a special wrapper that adds special features to an element. One of these special features the jQuery function adds is the css function. The css function takes in a JavaScript object that represents the CSS styles you'd like to add to the element. Notice that the syntax almost looks like regular CSS, except we're using it in JavaScript instead of a CSS file.

Adding CSS directly works fine, but we should be separating our presentation from our behavior. We can do this by defining the styles we'd like to add as classes in our JavaScript. We can then add the classes using jQuery.

In my CSS file:

  .list-style { background: blue; border: 5px solid black; }

In my JavaScript file:

  function changeStyle()
  {
      var element = jQuery(this);
      element.addClass('list-style');
  }

jQuery takes care of adding multiple classes, so you can add as many classes as you want:

  element.addClass('list-style');
  element.addClass('another-class');

Later, you can go back and remove classes as well:

  element.removeClass('list-style');

This is the preferred way of modifying the styles in your HTML, so try to avoid directly modifying the CSS styles of an object when you can.

See more on CSS manipulation with jQuery here.

jQuery Effects

jQuery offers a few built in functions for adding special effects to your page. These are pretty simple effects, but they can come in handy. There are additional effects that people have written that can be plugged in to jQuery, but, for now, we'll start with the simple built in ones.

Fading

Elements on your page can easily be faded in or faded out with jQuery:

  // Without a specified time
  element.fadeIn();
  element.fadeOut();
  
  // With a specified time
  element.fadeIn(1000);
  element.fadeOut(3000);

The the examples at the top fade the element in and out without specifying the amount of time it should take. The examples on the bottom are setting specific amount of time the effect should take. The effects functions take in the number of milleseconds an effect should take (there are 1000 milleseconds in one second).

See more on effects with jQuery here

Activity

Download the example jQuery files here. I will go over how each of the examples works and give you a chance to modify the scripts.

Assignment 3

Due Friday October 15th at 11pm

Download the template files here and make the index.html page behave the way it is described. Be sure to use proper indentation and variable/function names and add comments to any functions or variables that might be unclear to others.

Zip all of the files for your project and email them to me before the due date.

Feel free to email me at mephraim@colum.edu if you have any questions.