New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

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

By Chris Converse | Wednesday, June 25, 2014

Create a jQuery Carousel for Images

Displaying a series of photographs and images within a small area of a site can be challenging. The goal is to give folks a sense of the image while providing a navigation scheme to get a sense of the other images. Though this technique may be referred to as a carousel, or slider, the effect is the same.

A more literal navigation system for an image carousel is to align a series of images in a circle. This gives the user an interesting navigation experience in addition to getting a glimpse of the total number of images available.

figure_1_carousel-WEB

By Chris Converse | Thursday, June 12, 2014

Create a jQuery Slideshow

figure_1_slideshow_anatomy-600

The general goal of a web-based slideshow is to give your site visitors an optimized, easy-to-navigate image viewing experience. Since navigation can take up valuable screen real estate, many slideshows opt to use an overlay, or lightbox effect, to give users the option of viewing a larger version of an image.

By Chris Converse | Wednesday, May 07, 2014

Planning a Responsive Web Design

figure_2_alternate_content

As mobile web usage continues to rise, it’s increasingly important that your website functions across all types of devices and screen sizes. The smartest way to provide the best user experience (UX) for today’s technology is to create a website with a responsive design.

By Chris Converse | Friday, May 02, 2014

Build Interactive Websites with jQuery

Building Interactive Sites with jQuery

If you want to capture your audience’s attention, you have to provide a great user experience. An interactive website is one of the best ways to keep your users engaged and returning to your site. While interactive websites may look impressive, they don’t have to be difficult to create. With jQuery, you can achieve an interactive web experience rather easily.

Designed to simplify JavaScript scripting, jQuery is the most widely used JavaScript library in use today. You can quickly incorporate dynamic and interactive content into a webpage with just a few lines of code. jQuery simplifies JavaScript by providing shorthand commands for more complex functionality. In other words, you can get more functionality with less coding.

By Scott Fegette | Monday, March 24, 2014

Use jQuery Ajax to Load Remote Web Content

Use jQuery Ajax to load remote web content

What is Ajax?

Ajax stands for “Asynchronous JavaScript and XML,” a friendly term for when a webpage or application asks a server for new content, then displays it in the current page without having to reload. Although the X in Ajax originally stood for XML, the content being delivered often comes in a variety of forms today, including XML, HTML, JSON (JavaScript Object Notation), or just plain old text. Ajax content has become commonplace in modern web experiences, but writing the JavaScript required to actually load and display Ajax content by hand can still be a tedious process. And that’s where jQuery Ajax can step in to make your job easier.

How can jQuery help with Ajax content?

jQuery is a JavaScript library, which simplifies many tasks in JavaScript. It’s very popular with web designers and developers for dynamically updating a webpage’s Document Object Model (DOM), and changing its structure and content as needed.

Let’s dig into the basics of using jQuery to load Ajax content using a very simple example.

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 | Saturday, August 11, 2012

How to build a list-based app with jQuery Mobile

In this tutorial, I’ll show you how easy it is to create a list-based app with the jQuery Mobile framework in just a few minutes, and hopefully encourage you to give it a try.

jQuery Mobile is an excellent way to create web applications for mobile devices, but it suffers from a bit of a PR problem. When I first learned about the framework, I put it on my list of technologies I should investigate, but I figured that because it’s based on jQuery, I’d have to be a jQuery expert before I could use jQuery Mobile. I found that nothing could be further from the truth.

All that is needed to use the framework is some basic HTML knowledge. In addition, because the framework is built on top of jQuery, you get all of the functionality of jQuery in a way that is easily accessible.

What is the jQuery Mobile Framework?

jQuery Mobile is a framework for developing web applications for touch-optimized devices. A framework gives you a structure or methodology for doing something—in this case, for developing web applications.

Although you can use HTML and JavaScript to develop mobile-optimized sites, you’ll quickly run into some serious problems: Different devices and browsers treat your code differently, so you have to write a bunch of JavaScript to overcome device orientation and other issues. You also have to create styles for different items like list views, dialogs, toolbars, and so on. jQuery Mobile does all of that for you. It creates a code base that handles differences between devices with support for a large range of devices.

A quick example: a list-based app

So let’s get started with a quick example. I’m going to build a list-based app that will show a selection of photos. I’ll start with some super basic starter code for a normal page:


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>ListApp</title>
  </head>
  <body>
  </body>
</html>

This is pretty standard HTML code. Let’s add a header section to our body:


<div id="header">
  <h1>My Photos</h1>
</div>

And of course, we’ll need a footer. I’m going to add a navigation with fake links to some other potential pages:


<footer>
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">Photos</a></li>
      <li><a href="#">Info</a></li>
    </ul>
  </nav>
</footer>

Now we need some content. To keep things short for this article, I’m going to add just two photos to the mix, but you can add as many as you like. Since this is a list-based app, I’ll put the photos inside a list.


<article>
  <ul>
    <li>
      <a href="#">
      <h1>Miniature Doberman Pincher</h1>
      <img src="images/doggie_tn.jpg" alt="Min Pin" />
      <p>This is what happens when a
      friend brings a dog to the studio.</p>
      </a>
    </li>
    <li>
      <a href="#">
      <h1>Gummy Bears</h1>
      <img src="images/gummies_tn.jpg" alt="Gummy Bears" />
      <p>Three different poster boards...mirror for reflection,
      black for background white for highlights</p>
      </a>
    </li>
  </ul>
</article>

We encased our list inside an <article> tag, and inside each list item we have a link, which will eventually take us to a large version of our image and then a headline, a thumbnail, and a short description.

HTML site before adding jQuery Mobile.

So far this is just a regular HTML page. Let's now add the jQuery library. Since the app is based on jQuery Mobile, we’ll need to add that library too, as well as some styles that the library needs. The easiest and recommended way to do this is to copy three lines of code from the jQuery Mobile Download page.


<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>

You can put this code in between the <head> tags in your document (not to be confused with the <header> tags). These three lines tie in the CSS, the jQuery Mobile library, and the jQuery library. If you preview the page now, you’ll be able to see some slight differences in the look of the page. The background will be gray, and the fonts will be different. Not too exciting, but it means the library is already working. Here comes the exciting part.

Formatting a list view

Modifying our list so that it gets mobile device functionality is super easy: we just need to modify our <ul> tag to read like this:


<ul data-role="listview">

Your page should look something like this:

Mobile page with a formatted list view made using jQuery Mobile.

From someone who has written the CSS necessary to make a list look like this photo, this library has already saved me a ton of time.

jQuery Mobile uses the data-role tag to assign roles to regular HTML elements on a page. The reason it can do this is because of a really cool feature in HTML5: the ability to add a data-whateverattribute to any tag and store information that you can use to style elements and create interactivity.

Making the list searchable

For an even more impressive example of what the library can do, try modifying your <ul> tag like this to make your list searchable:


<ul data-role="listview"  data-filter="true">
 

You should see a search box appear on top of your list. Start typing the word gummy into the search box and you’ll see that the list only displays one item (the one with the text gummy bears in the title). jQuery Mobile does all of that for you automatically.

jQuery Mobile list view screen with a searchable list field.

Formatting Headers and Footers

Let’s add some of the other tags that tell jQuery Mobile to format things in a more mobile-friendly fashion.

Content in jQuery Mobile is normally placed inside a data-role="content" section. We can add that to our <article> tag.


<article data-role="content">

Let’s also fix up the header. We’ll use data-role="header" in the <header> tag.


<header data-role="header">

Next, we'll fix the footer. Modify the <footer> tag like this:


<footer data-role="footer" data-position="fixed">

Not perfect yet, but this shows a big improvement. Our header looks like a mobile device header, our search bar and list are nicely formatted. Notice that I’ve added the data-position=“fixed” attribute to the footer. That places the footer at the bottom on mobile devices. Our footer looks good, but the links could look better. Let’s make them look like buttons on a mobile device.

Modify the <nav> tag in the footer to read like this:

  <nav data-role="navbar">

jQuery Mobile list view page with search field and formatted headers and footers.

Our application is looking great; however, we could really use some icons on the navbar links. jQuery Mobile lets us easily add icons by adding a data-icon attribute to links by modifying our list items like this:


<li><a href="home" data-icon="home">Home</a></li>
<li><a href="Photos" data-icon="grid">Photos</a></li>
<li><a href="Info" data-icon="info">Info</a></li>

jQuery Mobile list page with added icons on the header and footer.

With just a few attribute tags, we’ve added mobile functionality to a page that would have taken hours to write and style otherwise.

Multiple Pages

So far, we’ve built a single page app. If you want to create an app with multiple pages, you have to wrap each page with a tag, use the data-role=“page”, and add an id so that we can link to that page.

Before the <header> tag add the following line of code:


<div data-role="page" id="photos">

And don’t forget to close it underneath the <footer> tag:


</div><!-- Page Photos -->

I always add a comment because when working on a large jQuery Mobile project, I use a lot of <div> tags and it’s nice to know what the closing tags belong to.

Now that we have a page, let’s add a page for each of our photos:


<div data-role="page" id="dog">
  <header data-role="header">
    <h1>Min Pin</h1>
    <a href="#photos" data-icon="grid" data-iconpos="notext">Photos</a>
  </header>
  <img src="images/doggie.jpg" class="fullscreen" alt="Min Pin" />
</div><!-- Page Dog -->

<div data-role="page" id="gummies">
  <header data-role="header">
    <h1>Gummy Bears</h1>
    <a href="#photos" data-icon="grid" data-iconpos="notext">Photos</a>
  </header>
  <img src="images/gummies.jpg" class="fullscreen" alt="Gummy Bears" />
</div><!-- Page Gummy Bears --> 

The code is pretty similar to the photo list page with some important changes. First, there is no footer on these pages, since they will just display the photos. Second, we added a header with a link back to the home page—note the data-iconpos attribute on that link. You can control the position of the icons on buttons with this attribute, or you can turn the buttons off altogether using notext as a value. The button on the header is linked to our photos page.

I’ve also added a class of fullscreen to my photos. This is not a jQuery Mobile class, but something I’ve added manually because I want the photos to display full screen, so eventually I’ll add some CSS for that further down. First though, we need to link the items in our list view page to our new pages. Modify the list like this:


<li>
  <a href="#dog">
  <h1>Miniature Doberman Pincher</h1>
  <img src="images/doggie_tn.jpg" alt="Min Pin" />
  <p>This is what happens when a
  friend brings a dog to the studio.</p>
  </a>
</li>
<li>
  <a href="#gummies">
  <h1>Gummy Bears</h1>
  <img src="images/gummies_tn.jpg" alt="Gummy Bears" />
  <p>Three different poster boards...mirror for reflection,
  black for background white for highlights</p>
  </a>
</li>

Our app is almost done. Now, right before the closing </head> tag at the top of our document, let’s add the style to make sure our photos fit.


<style>
  img.fullscreen {
    max-height: 100%;
    max-width: 100%;
  }    
</style>

jQuery Mobile list app modified to show fullscreen images.

Our app is now ready. You can take a look at the finished jQuery Mobile app here.

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

Suggested courses to watch next:• jQuery Mobile Web Applications• jQuery Mobile Essential Training• Mobile Web Design & Development Fundamentals• HTML5: Structure, Syntax, and Semantics

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

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.