Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to:...

13
In this lecture, we'll explore a variety of jQuery plugins that can help you add elegance and interactivity to your responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image slideshows with a responsive slider. Learn how to incorporate a modal dialog. Learn how to customize tooltips. Learn how to make a mobile friendly navigation menu. Enhancing Responsive Layouts With JQuery You can do a lot with just HTML and CSS (particularly HTML5 and CSS3), and we can design beautiful and beautifully responsive Web sites using only those tools. However, JavaScript—particularly the popular JavaScript library jQuery—can enhance your site in a myriad of ways, helping you create content sliders, incorporate interactive photo galleries, animate elements, and more. We touched briefly on jQuery Mobile in the last lecture. In this lecture, we're going to explore a handful of jQuery plugins that sharpen and expand your options for responsive designs. Follow along at the example site here , and be sure to check out the source code. Implementing JQuery Plugins Implementing jQuery plugins into your site is fairly easy, and as you move through this lecture, you'll notice a pattern in implementing a jQuery plugin. Once you link to the the main jQuery library in your HTML document, using a plugin usually involves the following steps: 1. Download the plugin files and upload them to your server. Minimally, the files include a JavaScript file, but they can also include CSS files. 2. Link to the script (and the CSS, if applicable) in the head of your HTML document. 3. Include a small script in your head as well, defining any plugin options as well as the plugin "trigger." This trigger, usually a class or id name, serves as a hook for the script, so the plugin knows which elements within CSS Layouts | Enhancing Responsive Layouts With JQuery

Transcript of Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to:...

Page 1: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

In this lecture, we'll explore a varietyof jQuery plugins that can help you addelegance and interactivity to your

responsive layouts.

In this lecture, you canexpect to:

Learn how toimplement jQueryplugins into your site.Learn how to enhanceimage slideshows witha responsive slider.Learn how toincorporate a modaldialog.Learn how tocustomize tooltips.Learn how to make amobile friendlynavigation menu.

Enhancing Responsive Layouts WithJQuery

You can do a lot with just HTML and CSS(particularly HTML5 and CSS3), and wecan design beautiful and beautifullyresponsive Web sites using only thosetools.

However, JavaScript—particularly thepopular JavaScript library jQuery—canenhance your site in a myriad of ways,helping you create content sliders,incorporate interactive photo galleries,animate elements, and more.

We touched briefly on jQuery Mobile inthe last lecture. In this lecture, we'regoing to explore a handful of jQueryplugins that sharpen and expand youroptions for responsive designs. Followalong at the example site here, and besure to check out the source code.

Implementing JQuery Plugins

Implementing jQuery plugins into your site is fairly easy, and as youmove through this lecture, you'll notice a pattern in implementing ajQuery plugin. Once you link to the the main jQuery library in your HTMLdocument, using a plugin usually involves the following steps:

1. Download the plugin files and upload them to yourserver. Minimally, the files include a JavaScript file, butthey can also include CSS files.

2. Link to the script (and the CSS, if applicable) in the headof your HTML document.

3. Include a small script in your head as well, defining anyplugin options as well as the plugin "trigger." Thistrigger, usually a class or id name, serves as a hookfor the script, so the plugin knows which elements within

CSS Layouts | Enhancing Responsive Layouts With JQuery

Page 2: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Don't try toreinvent thewheel, but domake sure youhave the latest

wheeltechnology: usean HTML5 based

responsiveframework togive yourself a

leg up onresponsive

designpreparation!

your document to act on.

4. Place these triggers (as class or id names) in therelevant HTML elements in the body of the document.

5. For some plugins, you have to add some additional CSSrules to your main CSS file.

HTML Layout Preparation

Before we dive into the plugins themselves, let's begin with our HTMLlayout. Note here that we're using an HTML5 based responsiveframework by Harry Roberts called inuit.css, which makes it easier forus to get up and running with a responsive design:

<head> <meta charset=UTF­8> <meta name=viewport content="width=device­width, minimum­scale=1.0, maximum­scale=1.0">

<title>Nine Muse Photography</title>

<!­­ The framework ­­> <link rel=stylesheet href="css/inuit.css">

<!­­ Your extension ­­> <link rel=stylesheet href="css/style.css"> <link href='http://fonts.googleapis.com/css?family=Mrs+Saint+Delafield' rel='stylesheet' type='text/css'>

<!­­ jQuery ­­> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script></head>

Note, first of all, our header. We've included a link to the latest versionof jQuery (as of this writing, 1.7.1). All of our plugins depend on beingincluded as part of the Web page. Now let's look at the code for ourlayout:

<div class="wrapper"> <div class="grids"> <div class="grid­12"> <header> <nav> <ul> <li><a href="#">Contact Us</a></li> <li><a href="#">About</a></li> <li><a href="#">Portfolio</a></li> </ul> </nav>

<h1>Nine Muse Photography</h1> </header> </div><!­­ /grid­12 ­­>

</div><!­­ /grids ­­>

Page 3: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

</div><!­­ /grids ­­>

<div class="grids"> <div class="grid­12"> <ul> <li><a href="#"><img src="img/pic1.jpg" alt="Picture 1" /></a></li> <li><a href="#"><img src="img/pic2.jpg" alt="Picture 2" /></a></li> <li><a href="#"><img src="img/pic3.jpg" alt="Picture 3" /></a></li> </ul> </div><!­­ /grid­12 ­­> </div><!­­ /grids ­­>

<hr>

<div class="grids"> <div class="grid­12 tagline"> We capture your most precious moments, beautifully. </div><!­­ /grid­12 ­­> </div><!­­ /grids ­­>

<hr>

<div class="grids"> <div class="grid­4"> [...] </div><!­­ /grid­4 ­­>

<div class="grid­4"> [...] </div><!­­ /grid­4 ­­>

<div class="grid­4"> [...] </div><!­­ /grid­4 ­­> </div><!­­ /grids ­­>

<hr>

<div class=footer> &copy;2012 Nine Muse Photography, All Rights Reserved </div></div><!­­ /wrapper ­­>

If you recall Lecture One, you'll find the layout's "grid" notation familiar.Here we have a twelve column grid. The header, photo section, andtagline all span the entire width of the page (all twelve columns). Thereis a middle div with some text, split into three columns. Each "row" isenclosed in a wrapping div, with the class name grids.

So far, our page looks like this:

Page 4: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Here's our original page running with our now familiar gridded layout system. Now let'sadd some responsiveness! Click here for a larger version of the image.

Photo credits: baby photo by 2nd Street Photography, wedding photo by Varin Tsai, andengagement photo by Seth Lemmons.

Notice how much screen real estate those three photos take up. The textis buried beneath them, demanding a lot of scrolling from the user. Let'sbalance things out and add some interactivity by turning that stack ofphotos into a slideshow with a responsive slider.

Responsive Slider

The Web is inundated with content slider jQuery plugins, but only a selecthandful of those are responsive (that is, the slider shrinks to fit whenviewed on a mobile device). For this example, we're going to useResponsiveSlides.js, a simple slider plugin by Viljami Salminen that islightweight, less then 1kb when minified, which means all unnecessarywhitespace and other characters (such as carriage returns) have beenremoved to optimize file size and reduce loading time for the user.

Once we download the plugin and include it in our file structure, we need

Page 5: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Look for plugins thathave been "minified"to be as lightweight aspossible. Remember:

everything you includeis something that hasto load when users

visit your page.

to pull it into our document. Include the following in the head section:

<script src="path/to/responsiveslides.js"></script>

The plugin also comes with a CSS file, which we'll need to include aswell. Add the file to your CSS folder, and link to it in your header:

<link rel="stylesheet" href="path/to/responsiveslides.css" />

Now, we need to include the following script in our header as well:

<script> $(function () $(".rslides").responsiveSlides( pager: true, speed: 500, maxwidth: 960 ); );</script>

This defines the "trigger" in our HTML—here, the rslides class—thatprompts the slider plugin. We're also setting some basic options: addinga pager and setting both the slideshow speed and the maximum width ofthe slider (which is just the width of the layout).

The advantage of this plugin is that it is completely customizable withCSS,which can also be a disadvantage, as you have to do quite a bit ofcoding to get the pagers and navigation buttons looking slick.Fortunately, the plugin includes some great demo files, from which wecan swipe the CSS we need:

.rslides margin: 0 auto;

.rslides_container margin­bottom: 50px; position: relative; float: left; width: 100%;

.rslides_tabs margin­top: 10px; text­align: center;

.rslides_tabs li display: inline; float: none; _float: left; *float: left; margin­right: 5px;

Page 6: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Shadows and bordersgive a sense of physical

substance to yourdesigns. For users, the

more tangiblesomething feels, themore it feels like theproduct of careful

choices, which (notcoincidentally) is thedefinition of elegance.

.rslides_tabs a text­indent: ­9999px; overflow: hidden; ­webkit­border­radius: 15px; ­moz­border­radius: 15px; border­radius: 15px; background: #ccc; background: rgba(0,0,0, .2); display: inline­block; _display: block; *display: block; ­webkit­box­shadow: inset 0 0 2px 0 rgba(0,0,0,.3); ­moz­box­shadow: inset 0 0 2px 0 rgba(0,0,0,.3); box­shadow: inset 0 0 2px 0 rgba(0,0,0,.3); width: 9px; height: 9px;

.rslides_tabs .rslides_here a background: #222; background: rgba(0,0,0, .8);

The rslides_tabs class encloses the pager, which is just an unorderedlist of links. The code above styles these links elegantly with shadows,borders, and rounded corners. Now our slideshow looks like this:

Page 7: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

A much more balanced layout, with an elegant image slideshow that features aresponsive slider. Click here to see the full layout in action.

Now that we've used jQuery to improve our management of screen realestate and add some interactivity, what's next? Well, if the user likeswhat they see, they'll want to know more, so let's use jQuery to help usgive the user an elegant way to get in touch.

Modal Window

What we'd like is a dialog that allows the user to send us a message,requesting a quote. To create an elegant modal window that pops upwhen the user clicks on a link, we're going to use leanModal, a jQueryplugin made by a Web design studio out of Australia called Finely Sliced.Again, there are quite a few jQuery plugins that do the same thing; we'repicking a minimal one that's small in size but gets the job done.

First, add a link to the plugin script in your header:

<script src="path/to/jquery.leanModal.min.js"></script>

Now, there are two parts to the window in our HTML: the content of themodal window, and the link to this content. Here's the content, whichyou'll notice looks similar to the code we used for our pop up dialog inthe last lecture:

<div id="quote"> <h3>Request a Quote</h3> <form action="form_action.php" method="get"> <label for="email">Email Address</label> <input id="email" type="text" placeholder="Email Address" size="30"/> <label for="message">Message</label> <textarea id="message" placeholder="Message"></textarea> <input type="submit" /> </form></div>

There's nothing out of the ordinary here: you have a standard form,enclosed in a div (note the id attribute). This content is hidden fromview until we trigger the modal window, so we can put this bit of codeanywhere. Here we've just included it at the bottom of the document.

Let's construct the link:

<p id="request"> <a id="modal_box" title="Tell us about your special event!" href="#quote">Request a Quote!</a></p>

The text here links to the modal box div we just made (via the hrefattribute), and we've also created a trigger here for the jQuery plugin bysetting modal_box as the value for the link's id.

Page 8: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Now we can add the following script in the header:

<script type="text/javascript"> $(function() $("#modal_box").leanModal(); );</script>

This defines the trigger for the plugin, so leanModal activates when thelink is clicked.

Finally, we add our CSS:

#lean_overlay position: fixed; z­index:100; top: 0px; left: 0px; height:100%; width:100%; background: #000; display: none;

#quote text­align: center; display: none; width: 300px; background­color: #c5a7a7; padding: 20px; border: 1px solid #3c1f1f;

#quote label display: none;

#quote textarea width: 250px; height: 200px;

#quote input width: 250px; margin­bottom: 20px;

The #lean_overlay CSS just styles the "dimming" effect when thewindow pops up, and was just copied and pasted from the plugin'sinstructions (here's the link again to the plugin's homepage). Theremaining code styles the modal popup window. Aside from making sureto set the display property to none (so it won't show up in thedocument's normal flow), you can style this however you like.

So now, when we click the "Request a Quote" link, our modal windowpops up and looks like this:

Page 9: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Don't dismissaspects ofdesign thatseem minor,

such as tooltips.Use jQuery

plugins to putpersonal

A simple and graceful modal box that allows the user to easily send a message—thanksjQuery!

So now we've got responsive sliders and a slick modal box. What's next?Let's look at how we can use another jQuery plugin to give us morecontrol over a small but useful feature: tooltips.

Fancy Tooltips

When you include a titleattribute in an HTML element,most browsers automaticallydisplays that title as a tooltip(right).

The default tooltip, however, lacks panache. The font and yellowbackground remind users of their operating system and distract fromyour design. Luckily there are many jQuery plugins that put a bit of styleback into the humble tooltip.

For our page, we're going to use the plugin Tooltipster, which islightweight and customizable.

Begin with loading Tooltipster's CSS file inside your header tag:

<link rel="stylesheet" type="text/css" href="css/tooltipster.css" />

Page 10: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

touches onsmall featuresand ensure a

consistent andcomprehensiveuser experience.

Then load Tooltipster's JS file after your jQuery inclusion:

<script type="text/javascript" src="js/jquery.tooltipster.min.js"></script>

Now, to activate Tooltipster we need to add the script within the header:

<script> $(document).ready(function() $('.tooltip').tooltipster(defaultPosition: "top"); );</script>

Here we set the "trigger" for the tooltip, a class we'll call, appropriately,tooltip. We also set the position of the tooltip: the tooltip pops upabove the titled element.

Finally, we need to add the class trigger within the body of thedocument. We only have one relevant title element we need to worryabout: the one in our "Request a Quote!" link. Let's add our classelement to it:

<p id="request"> <a id="modal_box" class="tooltip" title="Tell us about your special event!" href="#quote">Request a Quote!</a></p>

That's all there is to it! If we wanted to customize this further, we couldedit the CSS file that's included with the plugin. However, the default CSSstyling looks great, as we can see in our updated screenshot:

Our Tooltipster jQuery plugin has given us a more aesthetically pleasing tooltip, one thatmatches our design far better than the default.

If you'd like to see what's out there beyond Tooltipster, be sure to checkout the additonal options listed below for further inspiration:

Open TipTipped 4.0.10qTip2tooltipsy

With these elegance and interaction enhancements under our belt, let's

Page 11: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

turn our attention to device compatibility, specifically how to make ournavigation menu mobile friendly.

Responsive Navigation

When we created our responsive Web site in the last lecture, we createda nice responsive navigation menu that, when viewed on a mobiledevice, stacked the menu items vertically and made them finger­friendly. Overall, that's a good approach, and many Web sites use thattechnique for their responsive site. The only downside to this method issimilar to the issue we had with the photographs in the original versionof our photography site: the navigation menu (usually placed at the topof the mobile window) can take up valuable screen real estate, requiringthe user to scroll down to view the site's main content.

There are several jQuery plugins that minimize the space taken up bythe navigation menu on mobile devices. Some turn the navigation menuinto a dropdown menu. The plugin we'll be using, a simple responsivenavigation plugin by Kent Safranski, uses a toggle approach: when theuser clicks on a navigation link, the menu slides out from beneath it.

You might notice that this plugin appends the word "Navigation" to ournavigation menu and leaves it there even if you resize the browserwindow back out beyond the triggering width. Our focus here is onresponding to different devices and browsers, so we're not as concernedabout the user's potential ability to manually resize the page. But it'salways a good idea to stay aware of the limitations and tics of anyoutside plugins you incorporate into your work.

First, we need to add the plugin link to our header:

<script src="path/to/jquery.responsinav.js"></script>

Next, let's add the script to our header:

<script type="text/javascript"> $(function() $(window).responsinav( breakpoint: 650 ); );</script>

We only need to define one option here: the "breakpoint" screendimensions for the plugin. This defines the screen width that prompts thetoggled version of the navigation menu: if the user's browser width is650 pixels or smaller—which captures mobile devices—then the usersees the mobile friendly navigation menu.

Note that, unlike the other plugins we've covered in this lecture, wearen't specifying an id or class name that serves as a trigger. Thisplugin instead relies on a certain element structure as a trigger. In thiscase, an unordered list nested within the nav element. So because ournavigation menu already has an unordered list, we don't need to makeany changes:

Page 12: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Even if you've growncomfortable with your

design routines,remember that tools

evolve. Getting familiarwith HTML5 elementswill help you take full

advantage of thejQuery plugins that

rely on them.

<nav> <ul> <li><a href="#">Contact Us</a></li> <li><a href="#">About</a></li> <li><a href="#">Portfolio</a></li> </ul></nav>

Of course, this method, while elegantly simple, is rather limiting.

If you aren't using HTML5 elements—and thus aren't yet using nav—you're out of luck. Or, if you've, say, nested another div between navand the list, you're also out of luck. In that case, you may want to huntfor another plugin. However, for our purposes, with a navigation menumade up of one clean and simple unordered list, the plugin worksbeautifully.

But we will need to edit our CSS for the mobile version of the navigationmenu. While the plugin does a good job of creating a menu the user cantoggle on and off, it leaves it up to us to style it as we need to:

@media screen and (max­width: 650px) nav position: relative; top: ­30px; width: 100%; text­align: center; background­color: #c5a7a7; border: 1px solid #3c1f1f; font­size: 100%;

nav li width: 100%;

If you remember our last lecture, this should look familiar: we'veenclosed this specialized CSS within a media query, so that it onlyapplies when the screen size is 650 pixels or less. We've made a fewadjustments to the position, size, and colors of the menu. Most notablywe've made the list items the width of the browser screen to ensure thatthey stack vertically.

Also, if you examine the example page's CSS style.css code, you'll seethis media query comes after the rest of our CSS, and we've made sureto account for any inheritance issues in the various properties.

Now, when viewed on a mobile device, our navigation menu is tuckedaway when the page opens (left), and when the user clicks "Navigation,"the menu slides down (right):

Page 13: Enhancing Responsive Layouts With JQuery · responsive layouts. In this lecture, you can expect to: Learn how to implement jQuery plugins into your site. Learn how to enhance image

Viewed on a mobile device, the navigation menu snugly awaits a click, ready to slidedown its options, keeping our page finger­friendly while saving screen real estate.

We've enhanced our page nicely with jQuery, but really we've onlyscratched the surface of what jQuery can add to a site, both inherentlywithin the jQuery library as well as through the use of plugins. Look forother plugins that offer different approaches to the functionality exploredin this lecture, but don't stop there! Go out and explore the many effects,animations, and interface elements that jQuery can add to a page.

DiscussionShare your thoughts and opinions with your fellowstudents in the Discussion area.

ExercisePull together the techniques you have learned in thiscourse to create a mini site on the topic of your choice