Learn it fast with expert-taught software and skills training at lynda.com. See what you can learn

By Ray Villalobos | Thursday, December 27, 2012

Introduction to JavaScript templating using mustache.js

Recently I built a small website for an event in my area. This type of project required me to manage small amounts of data—information about speakers, bios, titles, and a description of the talks. I wanted to have a speakers page, but I also wanted a rotating promo built as a component I could use on the homepage, and on other pages to highlight the event’s speakers. That meant two different views for the same data.

This was the kind of problem I used to throw a quick SQL database at, but it really wasn’t worth the pain for this project as the amount of data was so minimal.  However, I didn’t want to resort to HTML because I knew the information would change often and be a pain to update. To solve the problem, I used a library called mustache.js. It’s pretty easy to use, and solves the problem with just a few lines of code.

Why mustache.js?

Mustache is a library that allows you to read in JSON formatted data and display it using templates you design with JavaScript. There are lots of similar libraries, such as underscore.js, handlebars.js, and dust.js. So why did I choose mustache?

By Ray Villalobos | Friday, September 21, 2012

Exploring browser animation options: Part two, jQuery

Animation can be accomplished in many ways with modern browsers. I’m currently working on a series of blog articles that explore some of the browser animation options available. In my last article, I looked at creating animations with CSS3 using keyframes and transitions. In this article, I’ll look at how to use jQuery to animate objects.

jQuery is a JavaScript library for building interactivity into web applications. One feature of jQuery is its ability to animate elements in HTML. This is quite powerful and useful because another feature of jQuery is its focus on remaining as backward compatible with older browsers as possible. This is significant because these two elements together make jQuery one of the most compatible of the animation options.

A good example of how to use jQuery animations can be found on my MexSantos MexSantos project, which is part of a creating Adaptive Website for Multiple Screens course I prepared for lynda.com.

The MexSantos website

If you click on one of the small thumbnails on the MexSantos website, you’ll see an overlay appear into view and then a copy of the photo in a larger view. The overlay animates subtly, but this is typical of the type of animation that jQuery is ideal for. Interface animations are its specialty and it handles them better than many other methods. jQuery uses JavaScript but one of its goals is to write JavaScript that is compatible with older browsers, so compatibility isn’t the problem with jQuery animations. The main issue is that jQuery animations require JavaScript, so unlike CSS they’re useless if the user has turned JavaScript off. This caveat can sometimes create usability concerns.

jQuery performs animations by modifying aspects of items on the page. For example, it can change the opacity of an image over time to make it look like it’s animated. Let’s take a look at the line of JavaScript code that adds the overlay in the MexSantos website:

#overlay {
    background: #000;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

One of the great things about jQuery is how commands can be chained together to create a sequence of events. In the JavaScript code above, we’ve managed to quickly create a div then assign it an ID of ‘overlay’ and append it to our body tag. To write the code that actually performs the animation, first we hide the element (otherwise animations show up immediately), and then we add a fadein() command. The fadein() method takes whatever the object is normally supposed to look like (based on CSS style sheets) and performs an opacity fade-in.

The CSS for the overlay ID is pretty simple: A black background with a fixed position that takes on the width and height of the entire window.

#overlay { background: #000; position: fixed; width: 100%; height: 100%; top: 0; left: 0; } 

To really understand what jQuery is doing, you need to look at the code as it animates. If you’re using a browser like Google Chrome with a dynamic code view, you should be able to right click on the background of the page and choose inspect element. Once you have inspect element open, make sure you’re in the elements tab and click on one of the thumbnails. Quickly look at the line before the closing tag. It should show the div being added dynamically and an opacity attribute with rapidly changing values.

jQuery rapidly animates the opacity value of our overflow element

The animate() method

There are a lot of other animation methods that can be used in addition to fadeIn(). Of course, where there is a fadeIn(), there logically is a fadeOut() method, but there are also others like slideDown(), and slideToggle(). Once you learn how to use one, the rest are pretty easy to pick up. There is also a generic method called animate() that allows more granular control over how animations are performed. These animation methods usually take parameters and callbacks as well. I’ve created an example that extracts the overlay functionality of the MexSantos website and shows how the generic animate() method can be used to control the CSS in objects.

jQuery Overlay

Here, we start off with an image that has a click event bound to it:

$('img.fooditem').click(function(e){
});

When someone clicks on the image, the fun starts. First, animate this element out of view with the animate() method, which allows you to change any CSS properties you want. For example, rather than just changing the fade, you can change the opacity as well as the position of the object.

//default animation for element
$(this).animate({
opacity: 0,
top: '+=200'
}, 500);

As part of the process, the animate() method takes in a JSON object that lets you modify CSS settings like the opacity and position of the element. You can also set the amount of time (for example, 500) you’d like the animation to take. jQuery has some predefined constants for animations such as fast and slow. Just like with the MexSantos example, we can add the overlay:

$('<div></div>').attr('id', 'overlay').appendTo('body').delay(300).hide().fadeIn(500);

We’re adding some delays because we want the animation of the image moving out of view to play before our overlay starts showing up. Now we can load the large version of the image:

$('<img>').attr('src',largeimage).attr('id', 'overlayimg').appendTo('#overlay').load();

With the large version of the image added, we need to know what to do once someone has finished looking at the overlay and clicks to return to the menu. We need to bind a click event to the overlay just like we did with the image, use the fadeOut() method to hide the overlay, and remove it from the page:

$('#overlay').click(function(e){
    $('#overlay').fadeOut('slow', function() {
        $(this).remove();   
    }); //fadeOut
}); //overlayclick

Finally, we’ll animate the image back into its original position.

$('img.fooditem').animate({
    opacity: 1,
    top: '0'
}, 500);

Conclusion

Animating with jQuery is like buying a car that is a “mechanic’s dream.” You really need to know your way around JavaScript, but there’s a real benefit in the backward compatibility with older browsers you gain. Using jQuery for browser animations is a strong route to take when working with complex interface interaction. Once you learn a few key concepts like binding methods and chaining commands, this type of animation actually becomes quite fun.

If you’re interested in writing code with jQuery, make sure you check out some of our offerings on jQuery animation in the lynda.com training library.

By Ray Villalobos | Friday, July 20, 2012

An introduction to LESS and Sass pre-processed CSS languages

Getting started on something new can be challenging, especially when the shear number of competing technologies that do similar things can make it tough to choose which one to give your attention to. One of the hot new trends in web design is CSS pre-processed languages and there’s two big ones vying for your attention—LESS and Sass. LESS and Sass are both ways of writing CSS code with a syntax that allows you to use features not yet available with Cascading Style Sheets (CSS), such as variables, nesting, conditionals, and more.

What are pre-processed CSS languages?

Pre-processed CSS languages add features to CSS that aren’t there yet—like variables, conditionals, and functions. They’re called pre-processed, because their final step is a processing, also called compiling, that converts the pre-processed language to regular CSS. In a nutshell, what you use on your site ends up being plain vanilla CSS, but comes as a result of processing the LESS, Sass, or other pre-processed language files you create.

Why use pre-processed CSS at all?

It’s hard enough becoming proficient with CSS, HTML, JavaScript, and jQuery, so if you can do the same thing with CSS, why would you want to submit yourself to learning an additonal language? Whether or not learning LESS or Sass is right for you comes down to whether or not the new languages will make you better, faster, or more efficient. Both LESS and Sass introduce variables into CSS, which I have found to be a very efficient detail that has made learning the new languages worthwhile for me.

For example, when you build a large web site, there’s usually a palette of colors you’re using throughout the site, and you might, for instance, be using one color for your article headlines that you also want to use on your links in the bottom navigation.

Example results of Less and SASS coding.

Example of web site design using the same color for article headlines and bottom navigation links.

Doing that with CSS is pretty easy:

<a href="http://blogldc.s3.amazonaws.com/wp-content/uploads/2012/07/CODE-11.png"><img class="aligncenter size-full wp-image-14227" src="http://blogldc.s3.amazonaws.com/wp-content/uploads/2012/07/CODE-11.png" alt="CSS code that alters the color text within a web design." width="506" height="55"></a>

While that works well, what if you wanted to use that same color in 20 or 30 selectors, or in gradients with a bunch of different browser prefixes? Both Sass and LESS will allow you to create variables which make global changes on elements a breeze. The code for this color application—with the assigned variable @myColor—looks like this in LESS:

LESS CSS pre-processed code that alters web design color. 

And—with the assigned variable $myColor—like this in Sass:

SASS CSS pre-processed code that alters web design color. 

Looks pretty much like CSS, right? Both LESS and Sass let you use the regular CSS code you already know so you really don’t have to learn a whole new way of doing things—just some additional rules. Even if the only thing you get out of pre-processed CSS is the ability to use variables, that alone will save you a lot of time, and it’s technology that saves you time that you need to spend your time investigating.

Using a Compiler application

Unfortunately, when you use pre-processed languages like SASS and LESS, you do need to compile the code into CSS. That can be done in a variety of ways. LESS, for example can be downloaded as a Javascript file that can be added to the project, or as a command-line tool for either your local machine or your server. Sass installation is also a command-line install. They try to make things easier by letting you define which folders should get automatically processed, but I still wouldn’t describe it as a user friendly experience for your average designer (which is why most graphic designers who use CSS have never tried using LESS or Sass).

Thankfully, there are some compiler applications that take care of processing files for you, and update things visually. My favorite application for compiling pre-processed languages is CodeKit. It handles LESS and Sass really well, and it also lets you process Haml, CoffeeScript, and even JavaScript.

A screenshot of the CodeKit compiler.

The CodeKit compiler.

You can also have CodeKit ‘mini-fy’ all of your files, not just your CSS. That means that it can spit out a different version of your code without comments, tabs, or extra spaces, which will make your files a lot smaller (something I recommend that you be doing regularly anyway).

If you use frameworks like BootStrap or jQuery Mobile, you can import them into your projects through CodeKit from a central location. When a new version of jQuery comes out, you can simply replace one copy and all of your projects will auto-update with the latest copy.

On a PC or Linux machine, things are a bit less rosy. There is a nice LESS compiler called SimpLESS which helps, but it’s not as feature-full as CodeKit.

Get Started

There are many more things you can do with LESS and Sass. If you’ve been on the fence about them, I recommend you give them a shot. Starting simply with variables is easy enough if you are already familiar with CSS, and if you’re like me, you’ll find using variables will make your life immediately easier. Even if you’re into command-line tools, I recommend you take a look at something like CodeKit or SimpLESS.

Should I use LESS or Sass?

Both LESS and Sass are pretty good, especially if you’re just getting started. For me, LESS has a bit of an edge since I’m currently digging into Twitter’s Bootstrap Framework, which makes it a breeze to scaffold and build web sites quickly (it is written in LESS). Sass takes the cake if you’re working with Ruby on Rails projects since it was written in Ruby. Ultimately, which pre-processed language you choose doesn’t really matter since they’re both tools that will make you more efficient, and that’s always worth an investment in time. Pick one and wedge it into the workflow for your next project. It may take you a bit longer to finish, but it will also change the way you code for the better.

Interested in more? • All web + interactive courses on lynda.com • All courses from Ray Villalobos on lynda.com

Suggested courses to watch next:CSS: Core ConceptsCSS FundamentalsCSS3 First LookManaging CSS in Dreamweaver

By Ray Villalobos | Saturday, June 16, 2012

Adobe Edge Preview 6: New features, and why you’ll love the Pin tool

One of the new projects from Adobe Labs I’m really excited about is Adobe’s interactive Animation tool for the web, Adobe Edge. It’s already in it’s 6th Preview Release, which means that although it’s not a fully developed product, it is a solid tool for building web animations that are compatible will all devices.

Adobe Edge uses web standards like HTML5, JavaScript, and jQuery to allow you to build animations that can be controlled through JavaScript. If you’re familiar with CSS or Flash, then Edge will be extremely easy to pickup. As a matter of fact, it’s a great tool for visualizing how CSS works. When you create elements in Edge, they are automatically Document Object Model (DOM) elements with properties like position, background color, borders, etc.

Animating toward a resting point with the Pin tool

I had an opportunity to meet with the Edge engineers during the last Adobe Max Conference and I found out that one of the exciting things about Edge is the way it reimagines the workflow for building web animations, and makes animation work easier and quicker.

When I create animations, I start by visualizing a resting point for my animation. In other words, a point that my animation’s elements will move towards, rest at on-screen for a few seconds, and then animate out of.

It’s generally pretty easy to design an animation resting point, but using a software like Flash, it can be challenging to animate to that point and then away from that point. The Adobe Edge Pin tool changes this by letting you complete a layout, and then pin or lock down the position of the elements in that layout, which allows you to then easily animate towards or away from that pinned position. It’s one of those things that takes a bit of an adjustment in your thinking to understand, but once you’ve mastered it, using traditional un-pinned keyframes seems like an outdated process.

Adobe Edge interface with Pin tool in timeline highlighted.

The Pin tool can accessed in several ways. Here we see the Pin tool highlighted as an icon within the timeline.

Adobe Edge Pin tool entry and exit animation.

In this image, within the red highlight box, you can see the Pin tool in action with the teal timeline areas representing entry animation, and exit animation—both created using the Pin tool to establish a "resting place" in the center of the animation.

Five note-worthy new Adobe Edge features

There are many new and cool Adobe Edge features worth mentioning, but here are five that I find particularly note-worthy:

• With the release of Preview 6, Edge has included the addition of symbols that can be exported and imported into new documents through Edge’s new .eglib format and, accordingly, allow you to reuse elements in animations.

• Edge can now be scripted with JavaScript or jQuery so you don’t have to learn a new language to build interactivity.

• A new Edge code editor allows you to quickly access any code in the timeline or attached to elements.

• You can now easily bring in custom fonts from an external library like Google Web Fonts.

The Preloader stage makes it painless to create custom preloaders from animated Edge clip-art, image assets, and text to be displayed in browsers when a user is experiencing connection or download delays.

Ready to check out Edge?

If you’re ready to give Adobe Edge Preview 6 a try, make sure to check out my Edge First Look Preview 6course on lynda.com to learn more about how to use the Adobe Edge timeline-based interface to create and build interactivity into your motion content.

Interested in more? • The full Edge First Look Preview 6 course on lynda.com • All web + interactive courses on lynda.com • All Adobe Edge courses on lynda.com • All courses from Ray Villalobos on lynda.com

Suggested courses to watch next:• Edge First LookCSS: Core Concepts• HTML5 First Look• jQuery Essential Training

By Ray Villalobos | Monday, June 04, 2012

Writing easier code using the jQuery JavaScript library

In a nutshell, jQuery is a JavaScript library that helps you get things done. It simplifies the process of accessing the DOM (Document Object Model) and supports older browsers. Let’s take a look at a simple example—say that you have an H2 in your page with an ID of ‘cathead’ and you’ve written it out like this.

 <h2 id="cathead">Consumer Widget</h2> 

If you wanted to modify the code to signify a color change when a person clicks on it, you could set up the code like this with JavaScript:


document.getElementById('cathead').onclick=function () {
  this.style.color='red';
} 

The first step the JavaScript takes is to search the DOM for an element with an ID of  ‘cathead’ and then bind an onclick event to it. It then uses the style property to change the color of the element to red. Pretty basic stuff. To do the same thing in jQuery, you’d write something like this:


$('#cathead').click(function() {
  $(this).css("color","red");
});

Other than this code being a lot shorter, the first thing that jQuery does is simplify the process of accessing the DOM. If you look at the two different code examples, you’ll see that jQuery uses the $() variable to gain quick access to elements. The great thing about jQuery is that you can use the $() to access any CSS property, not just IDs.

Let’s look at what happens if we make ‘cathead’ a class instead of an ID element because we have a bunch of headlines that we want to apply the color change to:


<h2 class="cathead">Consumer Widget</h2>
<h2 class="cathead">Another Widget</h2>

jQuery would do it like this:


$('.cathead').click(function() {
  $(this).css("color","red");
}); 

So, with jQuery, instead of selecting an ID, you pass along a class you want to select. You may be thinking that you could just as easily do the same thing by using JavaScript’s getElementByClassName—and you’d be right… sometimes. One main stumbling block is that the getElementsByClassName method is not available in a lot of versions of Internet Explorer, so—plain and simple—some browsers don’t support it. Plus, the getElementsByClassName method returns an array that you have to iterate through in order to modify each instance of the class, which means your code ends up being longer (a lot longer). jQuery on the other hand uses its own methods that are backwards compatible with older browsers and allows you to select the DOM in a variety of ways.

Here’s another example of why I prefer jQuery: While JavaScript has several methods for selecting elements, including the aforementioned getElementById(), getElementsByClassName(), getElementsByTagName() (you can find how well they’re supported in here: http://www.quirksmode.org/dom/w3c_core.html#gettingelements), jQuery only has one.

And that’s not where the magic ends. You can easily select every other element by doing something like this:


<h2 class="cathead">Consumer Widget</h2>
<h2 class="cathead">Another Widget</h2>
<h2 class="cathead">One More Widget</h2>
<h2 class="cathead">Last Widget</h2>
<script>
  $('.cathead:even').css("color","red");
</script>

or you can use its cousin…


$('.cathead:odd').css("color","red");

…which makes it trivial to do zebra striping table rows. Plus, jQuery has methods for animation, and easily building overlays, tabs, and other UI elements.

After you get started with JavaScript, jQuery is an excellent next library to learn. If you’re just getting started, I recommend you check out this week’s episode ofView Source where I show you how to use some basic jQuery to build a simple toggle tooltip.

Interested in more? • The full View Source weekly series on lynda.com • All web + interactive courses on lynda.com • All courses from Ray Villalobos on lynda.com

Suggested courses to watch next:• Create an HTML5 Video Gallery with jQueryCreate an Interactive Map with jQueryCreate an HTML5 Video Gallery with jQueryCreate a Rotating Carousel with jQuery

By Ray Villalobos | Monday, February 27, 2012

Using the jQuery UI library with Google’s CDN

The jQuery library gets a lot of coverage online at lynda.com. It’s a great way to build cross-platform interactivity into your websites with a minimum amount of effort. But you might not be familiar with its cousin, the jQuery UI library, which allows you to add tough-to-code widgets to your websites with just a few lines of code.

The JQuery UI  library screenshot

There are widgets in the jQuery UI library for all kinds of useful functionalities like drag and drop, buttons, dialogs, and progress bars. In fact, The jQuery UI library is so big it’s not even included in the normal jQuery library, and it comes as part of a separate download. In this week’s View Source tutorial, I will take a peek into the jQuery UI library to show you how to create a Datepicker you can use on your online projects.

Using the library is pretty simple. Let’s say you have this basic form:

1
2
3
<formaction="#"><label>When <inputid="datepicker"type="text"name="date"/></label></form>

First, you’ll need a copy of both the jQuery library and the jQuery UI library. If you don’t have the libraries already, Google and others keep copies of popular libraries online, so you can use a copy from Google’s CDN (Content Delivery Network). When you use a popular CDN like Google’s, it means that if someone visits a different site that uses the same library before coming to your page, it will be cached by your browser and available quicker to your users, which makes your page operate faster. Here’s two lines that will load up the libraries via Google’s CDN.

1
2
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>

This usually goes in the <head> section of your HTML page. In WordPress, you can update the header.php template by going to your dashboard, finding the Appearance panel, and then selecting the Editor option.

Next, you’ll need to pick a style for the calendar pop-up. You can do this yourself by using the jQuery UI ThemeRoller, or by using jQuery UI’s library of predefined styles. Just go to the ThemeRoller page and choose the tab labeled Gallery.

Example of pre-built ThemeRoller jQuery themes

Once you pick the theme you want, you can download the theme to your desktop and install it, or you can simply link to Google’s copy of one of the themes from the Google CDN. Here’s the formula:

1
<linkrel="stylesheet"href="http://ajax.googleapis.com/ajax/libs/jqueryui/[JQueryUIVersion]/themes/[ThemeName]/jquery-ui.css"/>

So in our case, since we’re working with version 1.8.17 of the UI, and the pepper-grinder theme, so we’ll use:

1
<linkrel="stylesheet"href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/pepper-grinder/jquery-ui.css"/>

The names of the other theme options are: base, black-tie, blitzer, cupertino, dark-hive, dot-luv, eggplant, excite-bike, flick, hot-sneaks, humanity, le-frog, mint-choc, overcast, pepper-grinder, redmond, smoothness, south-street, start, sunny, swanky-purse, trontastic, ui-darkness, ui-lightness, and vader.

Now that our setup is done, all we need to do is type in our jQuery code that links the form field to the widget. You should put this before the closing </body> tag in your document. In WordPress, that would be in your footer.php file.

1
2
3
4
5
<script>
$(function(){
	$("#datepicker").datepicker({});});</script>

The jQuery code looks for a form element with the ID of Datepicker and adds the functionality to that field. Here’s a full listing of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"/><title>DatePicker Sample</title><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script><linkrel="stylesheet"href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/pepper-grinder/jquery-ui.css"/></head><body><formaction="#"><label>
		When
		<inputid="datepicker"type="text"name="date"/></label></form><script>
	$(function() {
		$( "#datepicker" ).datepicker({ });
	});
</script></body></html>

There are a lot of other options you can use, and when working offline you should definitely include a call to a local copy of the libraries. To find out how to do this and more, check out this week’s free View Source tutorial called Creating a Datepicker for your forms with jQuery on lynda.com. If you’re a lynda.com member and want to learn more about how to speed up your site with content delivery networks (CDNs), check out the member-exclusive video called Using a CDN to speed up your website.

Interested in more? • The full View Sourceseries • All developer courses on lynda.com • All web + interactive courses on lynda.com • All courses from Ray Villalobos on lynda.com

Suggested courses to watch next:Create an Interactive Video Gallery with jQueryCreate an Online Photo Gallery with jQuery and DreamweaverCreate an Interactive Map with jQuery and DreamweaverjQuery Essential TrainingSet a Marquee to Autoplay with jQuery and Dreamweaver

By Crystal McCullough | Wednesday, July 28, 2010

Building cross-browser, interactive web sites with open-source JavaScript libraries

In Prototype and script.aculo.us Essential Training, Joe Marini introduces the concepts and techniques for using Prototype and script.aculo.us, two of the most popular open-source JavaScript libraries for building cross-browser, highly interactive, and visually appealing web sites. This course also covers installing each of the libraries and explaining their unique purposes, using simple CSS3 expressions to manipulate web content, working with events in a cross-browser way, and enhancing a real-world web site example to show different ways that the libraries can be used.

Get the latest news

  •   New course releases
  •   Pro tips and tricks
  •   News and updates
  
New releases submit clicked

You can change your email preferences at any time. We will never sell your email. More info

Featured articles

A lynda.com membership includes:

Unlimited access to thousands of courses in our library
Certificates of completion
New courses added every week (almost every day!)
Course history to track your progress
Downloadable practice files
Playlists and bookmarks to organize your learning
Become a member

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.