You are here: Home | teaching | Spring 2013

PopUp MP3 Player (New Window)

Digital Media For Designers II

Class 16

Last Class!

For our last class we are going to explore JavaScript, which is a browser or client-side, interpretive, scripting language that has been around since 1995, when it was called LiveScript and it was maintained by the browser company Netscape as a way of adding interactivity to web pages. We're going to be exploring JavaScript via jQuery, a very popular JavaScript framework that is currently blowing up huge. 

framework, in this sense, is a comprehensive library of shortcut methods (a.k.a. functions) and objects that are all built with JavaScript. In other words, developers took many of the functions and classes they had already been using in JavaScript, stuck them all in a single library file, and made them accessible with shortcut syntax that we call jQuery.

In Class Project: Create a Simple jQuery Slideshow

For this project, we will need these [project files] and this [tutorial PDF]. I have also created a tutorial video of this exercise:

 


We probably won't have time, but regardless I have prepared some more jQuery exercises that you can explore to get a firmer grip on the principles of this framework:

 

Example #1

We'll start with a simple example. Create an HTML doc with the following code and call it index.html:

<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title>
 <meta name="description" content="">
 <meta name="author" content=""> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="/css/style.css"> <script src="/js/libs/modernizr-2.5.3.min.js"></script>
</head>
<body>
 <p>
 jQuery is not loaded.
 </p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>window.jQuery || document.write('<script src="/js/libs/jquery-1.7.2.js"><\/script>')</script> <script src="/js/plugins.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
 

Then create the following CSS file and name it style.css:

body { font: 16px sans-serif; }
p { color: red; border: 1px solid red; padding: 5px; margin: 5px; }
p.tmpFrameworkLoaded { color: green; border: 1px solid green; }

and place the following JavaScript in a js/script.js file:

if ($) {
$(document).ready( function() {
$('p').addClass('tmpFrameworkLoaded');
$('p').text('jQuery successfully loaded and running!');
} );
}
 


Example #1 in action

In the previous code, we created a simple HTML5 document with nothing special in the body: 

jQuery is not loaded.

But if we then load this into a browser, we will see the following:  

jquery not loaded

This shouldn't be all that suprising, since that message appears in the HTML. But the jQuery code we place in script.js should have given us the following: 

jquery loaded

This example is a simple test to see if jQuery has loaded properly. Since we didn't download the jQuery library, it should be no surprise that it doesn't work. Downloading jQuery is easy: simply go to jQuery.com and click the btn downloadLarge button. Or just click the button image I have provided to open up the jQuery library file. However you retrieve it, you'll see that it is contained inside a single JavaScript file. This file will be saved into the js/libs folder:

jquery install

Once you have installed (a.k.a. saved) jQuery, open up your index.html file in a browser again to test it.


Example #1 Explained

So here's what is going on the previous example. The HTML is pretty simple: just a simple <p> tag with a default message in it. In the CSS file we created, this simple style declaration:

p { color: red; border: 1px solid red; padding: 5px; margin: 5px; }

which applies to all <p> tags in the HTML document, including the aforementioned <p> tag, and the message text within it. In the script.js file we have the following code: 

$('p').addClass('tmpFrameworkLoaded');

This code uses the jQuery object selector ($) and, in this case, it is selecting all HTML <p> elements. It is then calling the jQuery addClass function on all <p> tags, which attaches whatever CSS class name the function is passed as a parameter, adding to (and, in this case, overiding) whatever styles the tag had prior. In this case the class is .tmpFrameworkLoaded , the definition of which is defined in our CSS file:

p.tmpFrameworkLoaded { color: green; border: 1px solid green; }

The next line of jQuery uses the jQuery text function to change the text within all <p> and </p> tags to whatever string of characters is passed as a parameter: 

$('p').text('jQuery successfully loaded and running!');
 

If jQuery has indeed be loaded successfully, the $s, the addClass and text functions, and all that other jQuery syntax in our script.js file should work and we will be presented with an HTML document, altered directly in the browser, to look like this:

jquery loaded


How Is This Better Than Good Ole' JavaScript? 

I'm so glad you asked! Well, this is a simple example – realy only a couple of choice lines – that changes a few things around in our DOM (Document Object Model).  As simple as it is, however, if we wanted to do the same thing using standard JavaScript, with no APIs or frameworks, it would look like this:

window.onload = function() {
var $p = document.getElementsByTagName('p')[0];
$p.className = 'tmpFrameworkLoaded';
if($p.innerText) {
$p.innerText = 'jQuery successfully loaded and running!';
} else {
$p.textContent = 'jQuery successfully loaded and running!';
}
};

Yikes! Variable declarations?! getElementsBy TagName?! If/else statements?! That code is a hot mess! However, before jQuery was invented in 2006, this was the only way to do it. 


So What Makes jQuery Better? 

One thing that makes jQuery far easier to implement than standard Javascript is its selectors API. We're already quite familar with the concept of a selector: we've been using them constantly in our CSS files. In the following code snippet, body, a, and .highlight and all selectors:

body{ padding: 0px; margin: 0px; background: url("images/bg.gif") #ccc no-repeat; }
a:link, a:hover{ color: red; }
.highlight{ color: black; background-color: yellow; }

As you can see, selectors are what CSS uses to reference HTML elements in general, and class names and ID tag specifically, with the intent of making them look and feel a certain way. In jQuery the concept is the same, but rather than determine styling, jQuery determines behavior. Take the following HTML code...go on, literally take it, and save it as an HTML document.

Example #2: Controlling Links

<!doctype html><!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--><!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--><!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--><!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--><head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title></title>
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="/css/style.css"> <script src="/js/libs/modernizr-2.5.3.min.js"></script></head><body>
  <ul id=’tmpFavorites’> 
 <li><a href=’<a href="http://www.google.com">http://www.google.com</a>’>Google</a></li> 
 <li><a href=’<a href="http://www.facebook.com">http://www.facebook.com</a>’>FaceBook</a></li> 
 <li><a href=’<a href="http://www.apple.com">http://www.apple.com</a>’>Apple</a></li>
 <li><a href=’<a href="http://instagr.am/">http://instagr.am/</a>’>Instagram</a></li> 
 </ul> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script><script>window.jQuery || document.write('<script src="/js/libs/jquery-1.7.2.js"><\/script>')</script><script src="/js/plugins.js"></script><script src="/js/script.js"></script></body></html>

The HTML above contains a simple un ordered list of common links. Nothing special... We're going to add a stylesheet containing the following code:

body { font: 16px sans-serif; }ul { list-stlye: none; margin: 0; padding: 0; }a{ text-decoration: none; }

and finally we're going to place the following jQuery code in our script.js file

//create a new js object called tempExamplevar tmpExample = { 
    //create a member method called ready
    ready : function() {
        // Find and return all links in ul#tmpFavorites, found in the jQuery object ($)...
        //attach a click event to each link 
        $(‘ul#tmpFavorites li a’).click( 
          //pass the click event an anonymous function, with the event object ($e) as a parameter...
          function($e) {
            //use the preventDefault() function to inhibit the default link click action
            $e.preventDefault();
            //and instead open a new browser window (or tab)
            window.open(this.href, ‘CoolLinks’, ‘’); }
            //first parameter: the URL opened in the new window
            //second parameter: the name of the window or tab
            //third paramterL: a string containing window options, which we're leaving blank for now.
        );
    } };/*the above object and function doesn't get called until the entire document, and thus the DOM, has loaded. To make sure of this, we'll pass a reference to the tmpExample's ready function using the built-in jQuery $(document).ready*/$(document).ready(tmpExample.ready);

Example #2: Explained

The jQuery code above is fully commented, but here is a rundown of what it's doing: 1.) The tmpExample object is created, along with a member method entitled ready. Then it just sits there in memory. 2.) As soon as the DOM is fully loaded, jQuery calls the $(document).ready() function we placed inside our script.js file. But notice we also passed it a reference to the tmpExample.ready object method, declared above. 3.) Because we did this, the browser will also execute this code.   

This example demonstrates the essence of the jQuery selector API: after the DOM is fully loaded into the browser's memory, this bit of code:

$(‘ul#tmpFavorites li a’).click()

uses the main jQuery selector ($) and then more specifically selects all links with each list item of the unnumbered list with the #tmpFavorites ID. It looks a lot like CSS, and this is not a coincidence: the jQuery selector API was developed to be familiar to CSS developers…like us!


Example #3: Toggling a Popup Div

So let's try another example using selectors. Using the following HTML code:

<!doctype html><!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--><!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--><!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--><!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
  <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
      <title></title>
      <meta name="description" content="">
      <meta name="author" content="">
      <meta name="viewport" content="width=device-width">
      <link rel="stylesheet" href="/css/style.css"> <script src="/js/libs/modernizr-2.5.3.min.js"></script>
  </head>
  <body id='tmpDialogueExample'>
      <form action='javascript:void(0);' method='post'>
        <p>
          In jQuery, the selector API allows you to select elements from
          the DOM, just like you do in CSS stylesheets.  This simple dialogue
          contains a few selector API examples.
        </p>
        <p>
          <input type='submit' name='tmpDialogueOpen' id='tmpDialogueOpen' value='Open Dialogue' />
        </p>
        <div id='tmpDialogue'>
          <input type='submit' name='tmpDialogueClose' id='tmpDialogueClose' value='Close Dialogue' />
        </div>
      </form> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script> <script>window.jQuery || document.write('<script src="/js/libs/jquery-1.7.2.js"><\/script>')</script>
     <script src="/js/plugins.js"></script> <script src="/js/script.js"></script>
  </body></html>

and the following styles in a css/style.css file:

@charset "UTF-8";
/* CSS Document */body { font: 16px sans-serif; }div#tmpDialogue { display: none; position: absolute; top: 50%; left: 50%; width: 500px; height: 500px; margin: -251px 0 0 -251px; border: 1px solid blue; background: lightblue; }body#tmpDialogueExample div.tmpDialogueOn { display: block; }input#tmpDialogueClose { position: absolute; bottom: 5px; right: 5px; width: 100px; }

In our scripts.js file, place the following javascript:

var tmpExample = {
  ready : function() {
    $('input#tmpDialogueOpen').click(
      function($e) {
        $e.preventDefault();
        $('div#tmpDialogue').addClass('tmpDialogueOn');
      }
    );
    $('input#tmpDialogueClose').click(
      function($e) {
        $e.preventDefault();
        $('div#tmpDialogue').removeClass('tmpDialogueOn');
      }
    );
  }};$(document).ready(tmpExample.ready);

Example 3: Explained

On the surface, the above example works similar to the previous example: the jQuery ready function is called after the document loads. Chained to this ready function is our custom tmpExample.ready function. This function does two things:

    $('input#tmpDialogueOpen').click(
      function($e) {
        $e.preventDefault();
        $('div#tmpDialogue').addClass('tmpDialogueOn');
      }

1.)It attaches a jQuery click() event function to the first submit button in the HTML, labeled with the #tmpDialogueOpen ID attribute. This click function takes as its parameter an anonymous function. The event object ($e) is passed to it so that we can prevent the default action of this event:
$e.preventDefault();
. Finally, we add a class to the tmpDialogue div:
$('div#tmpDialogue').addClass('tmpDialogueOn');

This new class, you may notice, simply unhides the div#tmpDialogue, set to display:none; in the css.

    $('input#tmpDialogueClose').click(
      function($e) {
        $e.preventDefault();
        $('div#tmpDialogue').removeClass('tmpDialogueOn');
      }
    );


2.)tmpExample.ready also attaches a second click() event, as seen in the code just above. This event does something similar to the previous click() event, but in this case it is attached the submit button labelled #tmpDialogueClose, and it removes the .tmpDialogueOn class from the #tmpDialogue div. As #tmpDialogue's native style is to display none, this line of code essentially re-hides it.

The result is something like a kind of toggling popup window:

Screen Shot 2012-04-14 at 5.07.09 PM


Example #4: Refining Selectors

One more example, this time a little more advanced. [Click here] to see it in action. You can find the code [here].

Example #4: Explained

The HMTL is fairly straightforward: Two unnumbered lists and a section of links below it. Upon closer inspection, you will notice that nearly every tag is classed and/or IDed. For example: <ul id='tmpPlants'> and <li class='tmpVegetables' id='tmpOnion'>Onion</li>. This is done to achieve granular selection in jQuery (described below).

The CSS is also straightforward, with the only interesting style being this one:

.tmpExample {
          border: 1px solid rgb(200, 200, 200);
          background: #cbe5f8;
}

This is essentially a class that provides a light blue highlight to an element.

The jQuery code, inside the script.js file, uses the same surface logic as the previous examples: creating an object with a ready function, then calling that object.function when the document is fully loaded:

   var tmpExample = {
    ready : function() {
    (…)
}
$(document).ready(tmpExample.ready);

But it's the stuff after the tmpExample.ready function definition that is most interesting. tmpExample.ready is actually just a one line function:

      $('a').click(tmpExample.findElements);

It attaches a click() event to each link in the HTML, with the tmpExample.findElements function call passed as the click event parameter. This ensures that tmpExample.findElements function, defined below tmpExample.ready, is called whenever a link is clicked.

The Switch Statement

findElements() is actually pretty simply too, it just uses a code construct we haven't seen before: the switch statement. Switch statements are pretty universal throughout the programming world. They can be thought of as switchboards: the statement checks the given input value and, based on this value, fires off a specific set of instructions. In our example, the switch statement is looking for the ID of whatever link called the findElements() function:

 switch (this.id)

Then the statement defines eventualities for every link ID case we're interested in with case statements. Every case statement ends with the break; command. This exits the case, thereby exiting the swtich statment as well. Some examples of the case statements in our code: 
 case 'tmpSiblings':
 {
   $('li#tmpCarrot').siblings().addClass('tmpExample');
   break;
 }

–and–
 case 'tmpVegetables':
 {
  $('li#tmpOrange').prevAll('li.tmpVegetables').addClass('tmpExample'); 
  break;
 }

These cases simply add the .tmpExample class to specific list items, but notice how jQuery is going about selecting them: siblings(), prevAll(), children(), parents(), etc. These methods allow you to search and filter the selection results you obtain. More on this below.


A Rundown of the jQuery Filters

The previous example is really designed to show you all of the jQuery Selector API's filtering functions in a single script. Let's examine each on a case by case basis.

find(): The find() method lets you search for elements within a selection you’ve already made. Below, we select all ul tags, then find() all li tags within them so we can add the .tmpExample class to each one:

  case 'tmpFind':
 {
 // If the id of "this" <input> element contains "Find",
 // Do the find() example.
   $('ul').find('li').addClass('tmpExample');
   break;
 }

siblings(): The siblings() method lets you select all elements on the same hierarchical level as your main selection, in this case all other list items in the same list as <li id="tmpCarrot">:

 case 'tmpSiblings':
 {
   $('li#tmpCarrot').siblings().addClass('tmpExample');
   break;
 }

next(): The next() method lets you select the next sibling element in the HTML document:

 case 'tmpNext':
 {
   $('li#tmpBroccoli').next().addClass('tmpExample');
 break;
 }

prev(): Like next(), the prev() method lets you select the preceding sibling element in the HTML document:

 case 'tmpPrev':
 {
   $('li#tmpBroccoli').prev().addClass('tmpExample');
   break;
 }

nextAll() and prevAll(): these two methods work similarly to next() and prev(), except they select all sibling elements after and before your main selection respectively:

 case 'tmpNextAll':
 {
   $('li#tmpBroccoli').nextAll().addClass('tmpExample');
 break;
 }
 case 'tmpPrevAll':
 {
   $('li#tmpOrange').prevAll().addClass('tmpExample');
   break;
 }

This instance of the prevAll() method has been passed a parameter, which further narrows its searching power to only select those previous siblings of #tmpOrange that happened to have the .tmpVegetables class:

 case 'tmpVegetables':
 {
   $('li#tmpOrange').prevAll('li.tmpVegetables').addClass('tmpExample');
   break;
 }

parents(): not surprisingly, parents() selects all parents of a selected element. In this example, however, parents() is being passed a selector for the tmpSelection div, further narrowing it to just that parent:

 case 'tmpParents':
 {
   $('li#tmpCarrot').parents('div#tmpSelection').addClass('tmpExample');
   break;
 }

parent(): Note that parent() is different than parents() in that it only selects the most immediate parent of the select element:

 case 'tmpParent':
 {
   $('li').parent('ul').addClass('tmpExample');
 break;
 }

children(): this method can be used to select specific children elements of a selected element, in this case all h4 tags in the tmpList div:

 case 'tmpChildren':
 {
   $('div.tmpList').children('h4').addClass('tmpExample');
   break;
 }

not(): The not() method allows to essentially deselect specific elements. In the case below, we want to select all list items, except those with the .tmpVegetables class:

 case 'tmpNot':
 {
   $('ul li').not('li.tmpVegetables').addClass('tmpExample');
   break;
 }

slice(): this method takes a beginning index value and ending index value as its parameters, allowing you to select a range of elements within a selection.

 case 'tmpSlice':
 {
   $('ul#tmpAnimals li').slice(1, 4).addClass('tmpExample');
   break;
 }

add(): The add() method allows to make a selection and then add elements to it, useful for constructing complicated selections of elements. Below we make a standard jQuery selection of all list items in the tmpAnimals unnumbered list, then we add the tmpBroccoli and tmpPepper list items.

 case 'tmpAdd':
 {
   $('ul#tmpAnimals li').add('li#tmpBroccoli, li#tmpPepper').addClass('tmpExample');
   break;
 }

eq(): this method allows you to reduce a selection based on its index number. In the following example, we select all list items, which returns an array of all list items in the DOM. The then eq() method is chained to our selection and passed an index number of 10. Because indexes always start at 0, eq(10) selects the 11th list item in the DOM, i.e. "Buffalo":

 case 'tmpEq':
 {
   $('ul li').eq(10).addClass('tmpExample');
   break;
 }


Events in jQuery

Not surpisingly, event handlers in any programming language exist to deal with events: mouse clicks, mouse moves, drags, drops. In short, user interaction. Creating event handlers in oldschool JavaScript used to be really difficult, but jQuery makes it much easier. There are a few ways to deal with events in jQuery, but the bind() method is by far the easiest. 

The bind() method accepts two parameters: 

  1. the event name, such as ‘ready’, ‘mouseover’, ‘mouseout’, or ‘click’  
  2. a function call or anonymous function declaration (i.e. the entire body of the function is passed in as one lone parameter) 

Try the following example:

Example 5: the jQuery bind() method

[click here to see example 5 in action] [click here to download the Example 05 files]

 The bind() method simply attaches some other function or method to a particular event. In the case below, we have a very basic HTML5 document:

<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title>
 <meta name="description" content="">
 <meta name="author" content=""> <meta name="viewport" content="width=device-width"> 
 <link rel="stylesheet" href="/css/style.css"> 
 <script src="/js/libs/modernizr-2.5.3.min.js"></script>
</head>
  <body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>window.jQuery || document.write('<script src="/js/libs/jquery-1.7.2.min.js"><\/script>')</script>
<script src="/js/plugins.js"></script>
<script src="/js/script.js"></script>
</body>
</html>

And some simple CSS:

div {
    border: 1px solid rgb(200, 200, 200);
    width: 100px;
    height: 100px;
    margin: 5px;
    float: left; 
}
div.tmpExampleOver {
    background: #5092c5;
}
div.tmpExampleOn {
    background: #165b91;
}
 

and the following  jQuery code in our script.js file:

$(document).bind(
  'ready',
  function() {
    $('div').bind(
      'mouseover',
      function() {
        $(this).addClass('tmpExampleOver');
      }
    );
 
    $('div').bind(
      'mouseout',
      function() {
        $(this).removeClass('tmpExampleOver');
      }
    );
 
    $('div').bind(
      'click',
      function() {
        if ($(this).hasClass('tmpExampleOn')) {
          $(this).removeClass('tmpExampleOn');
        } else {
          $(this).addClass('tmpExampleOn');
        }
      }
    );
    
  }
);

 

The resulting index.html file, rendered in a browser, should look something like this:

example 05

[click screenshot to see the actual page in a browser]

As you can see, the six divs change background color as you hover the mouse over them (mouseover events), change back to their original background color when the mouse moves out (mouseout events) and toggles a dark blue background color when you click on any of them(click event). Let’s see how it works, shall we? 

Example 5: Explained

The HTML and CSS is fairly straightforward: six anonymous divs in the HTML, styled as six squares by the CSS. The CSS also has two additional classes: they add background colors for the mouseover state and the clicked state, respectively:

 
div.tmpExampleOver {
    background: #5092c5;
}
div.tmpExampleOn {
    background: #165b91;
}

 As per usual, the jQuery is where the interaction happens. The first thing that occurs is a use of the bind() method to attach further functions to the entire document when the ready event is detected:

$(document).bind( 'ready', ...)

The bind() method accepts two parameters: 1.)the event name, in this case ready and 2.) a function call or anonymous function declaration. We’ll be passing an entire anonymous function as one big parameter. The function we’re passing is really just three simple subroutines:

1.)To each div tag we’re binding a mouseover event function that adds the tmpExampleOver upon detecting any mouse over event:

    $('div').bind(
      'mouseover',
      function() {
        $(this).addClass('tmpExampleOver');
      }
    );

2.)Then to each div we’ll bind an event that essentially undoes what we just did when the mouse leaves the div area: 

    $('div').bind(
      'mouseout',
      function() {
        $(this).removeClass('tmpExampleOver');
      }
    );
 

And finally we’ll bind a click event to each div that adds tmpExampleOn class if it isn’t attached, and removes the class if it is attached: 

    $('div').bind(
      'click',
      function() {
        if ($(this).hasClass('tmpExampleOn')) {
          $(this).removeClass('tmpExampleOn');
        } else {
          $(this).addClass('tmpExampleOn');
        }
      }
    );


Advanced Event Handling 

As I said before, there a plenty of interesting ways to handle events in jQuery. The following example covers four of them:

Example 6: Advanced Event Handling Examples

[click here to play with this example in a browser] [click here to get the example code]

The HTML and CSS for this example is very similar to that of example 05 above, i.e. some anonymous divs styled to be 100px by 100px squares. The code found in the script.js file provides four different examples of the innovative and simple ways to deal with events. Each of these functions is declared when the document has loaded via this line of jQuery:

$(document).ready( function(){...});

Let’s examine each example. The first uses the standard bind() method we used in the previous example, but notice that it combines, or chains, three bind() methods together like so: $('div.tmpBind').bind(...).bind(...).bind(...); You may also notice that we’re using the find() method to find all children div tags within the div.tmpBind.

Example 06.01:

  function() {
    //Example 06.01: handling events with the bind() method:
    $('div.tmpBind').bind(
      'mouseover',
      function() {
        $(this).find('div').addClass('tmpExampleOver');
      }
    ).bind(
      'mouseout',
      function() {
        $(this).find('div').removeClass('tmpExampleOver');
      }
    ).bind(
      'click',
      function() {
        if ($(this).find('div').hasClass('tmpExampleOn')) {
          $(this).find('div').removeClass('tmpExampleOn');
        } else {
          $(this).find('div').addClass('tmpExampleOn');
        }
      }
    );
    //end of Example 01

 

Rather than bind(), Example 06.02 uses jQuery’s mouseover(), mouseout(), and click() methods directly to add event functions, chaining them together like so:

$('div.tmpIndividual').mouseover(...).mouseout(...).click();

 

Example 06.02:

 

/*Example 06.02: handling events with built-in jQuery event methods like mouseover(), mouseout(), and click():*/
    $('div.tmpIndividual').mouseover(
      function() {
        $(this).find('div').addClass('tmpExampleOver');
      }
    ).mouseout(
      function() {
        $(this).find('div').removeClass('tmpExampleOver');
      }
    ).click(
      function() {
        if ($(this).find('div').hasClass('tmpExampleOn')) {
          $(this).find('div').removeClass('tmpExampleOn');
        } else {
          $(this).find('div').addClass('tmpExampleOn');
        }
      }
    );
    //end of Example 02

 

Example 06.03 uses the very convenient jQuery hover() and toggle() methods.

The hover() methods takes two functions as parameters, following this pattern:

$(‘the_element’).hover(the function to be called when the mouse is moved over the_element,  the function to be called when the mouse is moved away from the_element);

 

The toggle() method is similar, except it deals with clicks rather than mouseover events:

$(‘the_element’).toggle(the function to be called when the mouse is clicked on the_element,  the function to be called when the mouse is clicked a again on the_element);

 

Example 06.03:

    /*Example 06.03: handling events with the jQuery's hover() and toggle methods:*/
    $('div.tmpPattern').hover(
      function() {
        $(this).find('div').addClass('tmpExampleOver');
      },
      function() {
        $(this).find('div').removeClass('tmpExampleOver');
      }
    ).toggle(
      function() {
        $(this).find('div').addClass('tmpExampleOn');
      },
      function() {
        $(this).find('div').removeClass('tmpExampleOn');
      }
    );

 

And finally Example 06.04, which uses JavaScript methods focus() and blur() to deal with what happens when a browser gives focus (or removes it) from different user interface elements. In this case, we have a simple <textarea> tag. Users can ‘focus’ on things like textareas or input boxes by using the tab key on their keyboard, or by clicking on them directly. ‘blur’ refers to what happens when the user tabs away or clicks somewhere else. Using the focus() and blur() methods, we can define event functions for precisely this type of user interaction:

Example 06.04:

    /*Example 06.04: handling focus and blur events with the focus and blur methods:*/
    $('div.tmpTrigger textarea').focus(
      function($e) {
        $(this).addClass('tmpFocused');
      }
    ).blur(
      function() {
        $(this).removeClass('tmpFocused');
      }
    );
 
    $('div.tmpTrigger textarea').focus();
  }

 

Above we are essentially adding the class .tmpFocused when a user focuses on the textarea in div#tmpTrigger, then removing that class when focus is removed, or blurred, as it is called. Also notice the last line in the function: 

$('div.tmpTrigger textarea').focus();

This forces browser focus on our textarea. Just calling the focus() method on a focussable element like <textarea> will give it immediate focus in the browser. (Note that with HTML5, this can be done without any JavaScript at all, as it is a built-in property of the new HTML5 form elements. However, it’s always nice to have fallbacks.) 

Post-Midterm Project

Project: Word & Image Typographic Animation

For this project, you will be creating a short promotional animation from your Word & Image II project using a type treatment you’ve developed in that class. The animation will be based on the composition and concept you have already created, but compositionally reformatted for widescreen presentation. [Click Here] to download a PDF of the following info.

Context:

Your final animation will be flexible to serve 2 out of the following 4 basic functions:

1. BROADCAST PROMO
A teaser animation promoting the event for which you are designing, to be aired on television during commercial breaks and/or on a venue monitor promoting upcoming events.

2. TITLE/CREDIT SEQUENCE
The opening or ending credits acknowledging the cast/creators/members of the event for which you are designing.

3. LIVE VISUALS
A live visual presentation projected on a screen or stage.

4. WEBSITE INTRO ANIMATION
An intro animation/splash page for the website related to your project.

Process:

You will start by choosing a typographic composition from your work in Word & Image 2 and deciding on the 2 contexts for your animation. You will sketch some loose storyboards which you will use to then create your refined boards/styleframes. These styleframes will be brought into After Effects and paced out to the final timing to create your animatic. The animatic is essentially a slide-show of your styleframes for timing reference.

With your styleframes and animatics as reference, you will create a 5-15 second animation in After Effects. The animation should resolve on key information about the event, with 5 seconds of pad (15 seconds becomes 20 seconds) so the viewer has time to process the information.


Requirements:

1920x1080 Horizontal Composition
• Camera + 3D Layers
• Incorporate sound design
• 5-15 seconds (+5 sec pad on resolve)
• Animation must match storyboards/styleframes
• Resolve with key information

Project Schedule:

04.04.13: Styleframes and animatics DUE

04.11.13: Rough animation DUE

04.18.13: Final animation DUE

Storyboards — Through a series of still frames, a storyboard illustrates all key moments of an animation, in a sequence that implies how one moment leads to the next. Transitions and camera movements can be noted underneath or between frames. Often times storyboards are rough sketches, rather than showing final artwork and design style.

Style Frames — Like storyboards, style frames involve a sequence of still images, but are designed in the specific style of the final animation. Choices such as typeface, final imagery, texture, and overall look & feel are shown in these frames, without any animation necessarily having taken place yet. A client would sign off on these frames, knowing exactly what the final product would look like, short of specific animation choices.

Course Details

Course Number: VDE2460 

Term: Spring 2013

Days: Thursday

Class times: Group 1: 12:30 - 3:20, Group 2: 4:30-7:20

Location: Visual Arts Building, Room 1018B

Description [Download Course Syllabus]: This course will explore the concepts of design for interactive and motion based media. Students will be introduced to the core online and motion design software programs, focusing on Dreamweaver CS6 and After Effects CS5. Students are required to use a sketchbook to develop concepts and storyboards for individual assignments and projects. Over the course of the semester students will develop individual projects using the technical skills and concepts learned in class.

Grading Policy

Final Grade will be determined by the following:

  • 10% Participation
  • 45% Assignments
  • 45% Main Project

Assignments/projects are graded on how each student meets the criteria of the particular project or assignment, how much time, effort and creativity went into the project. Students are expected to demonstrate hard work, commitment and show individual improvement and personal growth through the course.

Grading Scale

A=Superior

B=Good

C=Satisfactory (minimum grade needed to advance to the next level)

INC=Incomplete*

W=Withdrawal Chosen by the student up to the ninth week of the semester

WF=Withdrawal Failure (assigned by faculty) signifies non attendance and failure to petition for a grade of W. This grade is factored as an "F" in determining a student's GPA.

*This grade is reserved for those cases when a student cannot for reasons beyond his/her control (accident or extreme illness) complete the course obligations. A student must petition the faculty for an incomplete. The work must be completed within four weeks of the beginning of the following semester. (A student on academic probation may NOT elect to receive an incomplete for any course)

Attendence Policy

Attendence to all classes is expected. There are no acceptable number of absences. Three unexcused absences will result in failure for the class. Two lates are the equivalent of one absence. Leaving a class early is considered equivalent to arriving late.

All assignments and projects are due at the beginning of class.

Three unexcused absences will result in failure. Two lates are the equivalent of one absence. Leaving a class early is the equivalent to arriving late.

Week 1

 Welcome to class!

What Are Motion Graphics and Why Should I Care?

I'm glad you asked. [Click here] for some of my favorite (and some of my own) uses for motion graphics.

Introducing the After Effects Interface

Let's begin looking at the After Effects interface to explore where things are and what they do. [Click here] for a PDF reference for the AE interface. I also made a reference video that covers all the topics I go over in the PDF:

Homework

Create this simple bouncing ball animation:

To help you do this, I have created a [PDF tutorial] that explains every step. In addition, I have taken the liberty of creating a video tutorial – in two parts – that you can watch:

Bouncing Ball Animation Tutorial – Part I

Bouncing Ball Animation Tutorial – Part 2

 

 

 

 

Week 2

From Bauhuas to Our House

O beautiful, for spacious skies, for amber waves of grain, has there ever been another place on earth where so many people of wealth and power have paid for and put up with so much architecture they detested as within thy blessed borders today?

-Thomas Wolfe

 

Today's class: 

  1. Let's look at some of your bouncing ball exercises. I want to go over any questions or issues that arose while working on this exercise.
  2. For today's exercise, we're going to explore a peculiar effect of vision referred to as [parallax]. The best part: we're going to do so by making the short tribute video, seen above,  celebrating the original members of The Bauhaus.

The details: I have prepared a [PDF and exercise files] for this lesson to help you along in creating the animation.  [Here is the font file].

I've also prepared a two-part tutorial of the above exercise:

 

 

 

The homework: Create your own short that exploits the parallax effect. Here is what I want to see from you next week:

  1. A styleframe or composition that you intend to animate. You can use a composition you have already created that you now like to animate, or you can create an entirely new composition just for this project.
  2. A rendered piece of video, nothing longer than 10 seconds (5 would be ideal).
  3. We will conduct a short crit next week to see what yaul have done!

Week 3

Mobile Apps(!)

But first...

  • Let's critique what you all did for your 3D parallax exercise.
  • I want to go over some layer-specific details, covered in this [tutorial PDF] I have prepared for you. 
  • Let's discuss a possible usage for precomposition. I created this tutorial on how precomps and nesting really come in handy. I have also posted the files I am using in this exercise, including the After Effects project. [Click here] to download them. 

    • Ok, let's discuss mobile applications.
    • HW: Come up with your own concept for a mobile application. It can be a better looking texting application; or a fun game; or maybe you've been thinking of a great app idea for some time. Now's the time to sketch it out and make a mockup composition. Take your sketches and create a Photoshop or Illustrator composition. Here are the details:
      • an [elevator pitch] describing your mobile app concept. One to two sentences please! 
      • sketches of how you might execute the interface design of the above concept. Here are examples of my sketches:

        main-menu card edit-screen-flow
        button-states warning-alert

      • fleshed out Photoshop or Illustrator compositions of your best sketches, presenting us with 2-5 screenshots that demonstrate how the application behaves.   
      • If you would like to employ Apple's native iOS6 graphical user interface (GUI) elements in your app designs, [click here] to download a Photoshop file containing every conceivable element you would ever need: keyboards, buttons, labels, chrome, navigation, maps, etc. (courtesy of  [http://www.teehanlax.com/])

    Week 4

    Sound Design and Advanced Animation

    1.)We'll begin by having you all present your mobile application concepts. We want to see the following:

    a.)Your elevator pitch

    b.)Your design sketches

    c.)PhotoShop/Illustrator mockups

    2.)Then we'll talk about sound design in After Effects. I've included a short tutorial video that covers one of the ways I use sound in After Effects:

    Introduction to Audio Syncing in AE

    3.)Then we'll use some sound and advanced animation to create a logo animation for your mobile apps.

    Here is a demonstration of my logo animation for my Bar Tab application:

    Bar Tab Logo Animation

     

    [Below is a 40 minute tutorial detailing how I went about making the logo animation:]

    Bar Tab Logo Animation Tutorial

    [Download the files for this exercise here]

    4.)Homework: create your own logo animation for your mobile app demo video. You'll be drawing from your graphic design backgrounds here to develop a logo that befits the app concept you introduced today. Create a short, elegant animation (no more than 5-6 seconds) for your logo that has a meaning relvant to your concept. 

    Week 5

    The First Draft...

    Below is the first draft of the demo animation for my Bar Tab mobile app. There is still a lot I would like to add to it, but the basic screen motion is presented here:

     

    Optimizing Your After Effects Project for Render

    The video tutorial below just goes over last minute steps I took to optimize the performance of my app animation AE project, both for RAM Preview performance and final rendering. Without going through with the steps outlined below, I was looking at a few hours render time for a 45 second video. Redic.

    Topics covered: Scripting, Pre-rendering and Save Frame As

    Here is a link to the [Selected_Comps_Changer script] I use in the above tutorial, and the [main scripts page] I found it on, www.crgreen.com

    Here is the link to the [frame rate calculator] I use in the above example.

     

    Finishing the Main App Animation

    After doing the necessary preparation above, it's now time to actually finish this app animation. I do so in the following tutorial video:

    Week 6

    Class 10 - March 5

    Read more:

    Week 7

    Week 7 content

    Week 9

    Happy Birthday (sigh)

    it's my birthday, so today we're going to create a 3D cupcake in Cinema 4D! The original tutorial that I am referencing for this exercise can be found [here].

    Word & Image Typographic Animation

    After today's class, we will begin work on the next After Effects Project. [Click here for the project description].  Here is what I will be working on to help you understand the stages of the project: a short PSA (Public Service Announcement) for Earth Day that focusses on the real world value of a one degree difference on your thermostat. Here is the preliminary script:

    Think one degree is 'no big deal'
    one degree can:
    Raise your heating costs by as much as 3 percent.
    Or it could Increase the nation' energy usage by and estimated 7 and a half billion dollars...
    1 degree globally would increase rain fall by as much as 10% in some areas, but cause severe draughts in other areas. Weird huh?
    One degree is a bigger deal than you might think...
    What can we do about it?
    Lowering your thermostat by one degree could save you as much as five percent on your heating costs!
    It will help lower fossil fuel consumption, save you money, it may even help save the world!
    So please remember: one degree is a big Big BIG deal!

    Here are some preliminary sketches:

    1Degree sketches

    Here are my thumbnails... something like a quickly sketched out storyboard:

    1Degree storyboard

     

    Week 10

    Project Update

    Storyboards, Styleframes, Animatics:

    Today our initial deliverables are due. This includes our storyboards, styleframes and animatics. Here are mine for your review:

    Styleframe:

    one degree styleframe

    Storyboards: 

    board-001

    board-002

    board-003

    board-004

    Animatic:

    This weekend I was able to record the voiceover for my piece, so I went ahead and pieced together my animatic. Remember, the animatic is a very rough version of your animation – kind of like a slideshow if your storyboards – that explroes and communicates pacing, editing, and audio choices. It merely shows us the intended flow of the finished piece. It also allows us to make comments on what's working and what ain't. All projects are different, and you may not even be sure what kind of audio you want to use. Not to worry: demo music or scratch tracks are often used in lieu of finalized audio for animatics. 

     


    If We Have Time:

    It would be nice to actually, you know, learn more things about After Effects! Therefore, here are some lessons I have prepared which will allow us to do just that. 

    Layers in After Effects [PDF] [Source Files]

    Masking in After Effects [PDF] [Source Files]

     

    Week 11

    I'm finished!

    Week 13

    HTML!

    Ok, we made it through After Effects. This leaves HTML and CSS to contend with. HTML (HyperText MarkUp Language) has gone through a lot of changes. Developed by Tim Berners Lee in 1980, it has gone through many iterations and updates, and has evolved from a humble markup language to the accepted information presentation technology of the 21st century. To save time, we'll be learning HTML5 tags and document structure, as these are the standards that, for the most part, will be used well into the future.

    • Introduction to HTML5
    • Let's build a simple HTML5 document.
    • CSS (Cascading Style Sheets)
      • What is CSS?
      • Examples
      • The Box Model

     

    CSS Syntax
    SelectorDeclarationDeclaration
    p
    {text-decoration: underline; padding: 15px;}
      property value property value

     

    • Wireframing
      • A wireframe, at its heart, is just a very bare-bones, skeleton layout for a website. Below is an wireframe example that employs a header, footer,  left content, and right column:
      • wireframe boiler
      • I would like to use a different layout standard, referred to as something along the lines of  '3 column fixed, header and footer'.wireframe HTML5

        As you see above, I have labeled all the areas with the approriate tag names. We'll build this site next week, but for now I just want you to think about site layout. The one above is fairly standard, but even if you feel like breaking from accepted standards, you'll find that you'll still need to layout your site in a similar manner. Even if you want your final product to look completely different, you're still using the same web standards to build it, and thus must choose a place for things that all good website designs need: a header, a footer, a main content area, and persistent navigation.

      • There are best practices for creating a site's visual designs, and they begin with a good wireframe. You can look at a preview of mine's below, yo. You all know PhotoShop and Illustrator really well, and you have a good deisng sense. But in case you were interested in how I made my wireframe, download this [Making a Wireframe tutorial PDF]. 
      • farmhouse wireframe
    • CSS for Layout: Let's try to build a 3-column, header, and footer layout by hand. Yay!!! [Project files can be downloaded here]. 
    • Slicing
      • PhotoShop and Illustrator perform a wonderful task called slicing to cut up sections of a composition and export it into images, HTML, and CSS. But be forwarned, it doesn't do a very good job. Let's take a look at the .PSD I have already sliced up in PhotoShop. The original .PSD, along with an HTML4.01 version of the resulting site, file can be found [here].
      • For a look at how I went about slicing this document, take a look at this [Slicing tutorial PDF].
    • Homework
      • Create your own wireframe, either in PhotoShop or Illustrator. Try  

    Week 15

    The Farm at Richville

    a fake website

     


    1.) The Exercise Files

    [Click Here] to download the wireframe .PSD file and the completed HTML and CSS website.

     


     

    2.) Farm at Richville – Setting Up the Site

     


     

    3.) The Farm at Richville – Configuring the HTML and assets

     


     

    4.) The Farm at Richville – Configuring the CSS – Part I


     

     

    5.) The Farm at Richville – Configuring the CSS – Part II

     


     

    6.) The Farm at Richville – Configuring the CSS – Part III

     

     

    You are here: Home | teaching | Spring 2013