Web Development Recipes

Transcription

1 Extracted from: Web Development Recipes This PDF file contains pages extracted from Web Development Recipes, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printer versions; the content is otherwise identical. Copyright 2010 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. The Pragmatic Bookshelf Dallas, Texas Raleigh, North Carolina

2

3 Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at The team that produced this book includes: Susannah Pfalzer (editor) Potomac Indexing, LLC (indexer) Kim Wimpsett (copyeditor) David J Kelly (typesetter) Janet Furlow (producer) Juliet Benda (rights) Ellie Callahan (support) Copyright 2012 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: Printed on acid-free paper. Book version: P1.0 January 2012

4 Problem When we need to present long, categorized lists on a website, the best way to do it is with nested, unordered lists. However, when users are presented with this kind of layout, it can be hard to quickly navigate, or even comprehend, such a large list. So, anything we can do to assist our users will be appreciated. Plus, we want to make sure that our list is accessible in case JavaScript is disabled or a user is visiting our site with a screen reader. Ingredients jquery Solution A relatively easy way to organize a nested list, without separating the categories into separate pages, is to make the list collapsible. This means that entire sections of the list can be hidden or displayed to better convey selective information. At the same time, the user can easily manipulate which content should be visible. For our example, we ll start with an unordered list that displays our products grouped by subcategories. Download collapsiblelist/index.html <h1>categorized Products</h1> <ul class='collapsible'> <li> Music Players <ul> <li>16 Gb MP3 player</li> <li>32 Gb MP3 player</li> <li>64 Gb MP3 player</li> </li> <li class='expanded'> Cameras & Camcorders <ul> <li> SLR <ul> <li>d2000</li> <li>d2100</li> </li> <li class='expanded'> Point and Shoot

5 6 <ul> <li>g6</li> <li>g12</li> <li>cs240</li> <li>l120</li> </li> <li> Camcorders <ul> <li>hd Cam</li> <li>hdr-150</li> <li>standard Def Cam</li> </li> </li> We ll want to be able to indicate that some of the nodes should be collapsed or expanded from the start. It would be tempting to simply mark the collapsed nodes by setting the style to display: none. But that would break accessibility since screen readers ignore content hidden like this. Instead, we re going to rely on JavaScript to toggle each node s visibility at runtime. We did this by adding a CSS class of expanded to set the initial state of the list. If we knew the user wanted to look at Point and Shoot Cameras when they first reached this page, for example, this markup wouldn t show the limited list yet. Right now it will show the full categorized product list, as shown in Figure 13, Our full categorized list without collapsibility, on page 7. But once the list is made collapsible, the user would see only the names of the products they were looking for, as shown in Figure 14, Our collapsed list, on page 7. Then, without navigating away from the page, they can still choose to look at any of our other product categories. Next we need to write the JavaScript for adding our collapsible functionality, as well as some Expand all and Collapse all helper links at the top of the list. Notice that we re adding the links via the JavaScript code as well. Like the collapsible functionality itself, we don t want to change the markup unless we know this code is going to be used. This also gives us the advantage of being able to easily apply this behavior to any list on our site without having to change any markup beyond adding a.collapsible class to a <ul> element. To start things off, we will write a function that toggles whether a node is expanded or collapsed. Since this is a function that will act on a DOM object, we will write it as a jquery plug-in. That means we will assign the function

6 7 Figure 13 Our full categorized list without collapsibility Figure 14 Our collapsed list definition to the jquery.fn prototype. We can then trigger the function within the scope of the element that it was called against. The function definition should be wrapped within a self-executing function so we can use the $ helper without worrying about whether the $ helper has been overwritten by another framework. Finally, to make sure that our jquery function is chainable and a responsible jquery citizen, we return this. This is a good practice to follow when writing jquery plug-ins; our plug-in functions will work the same way that we expect other jquery plug-ins to work. Download collapsiblelist/javascript.js (function($) { $.fn.toggleexpandcollapse = function(event) { event.stoppropagation(); if (this.find('ul').length > 0) {

7 8 event.preventdefault(); this.toggleclass('collapsed').toggleclass('expanded'). find('> ul').slidetoggle('normal'); return this; )(jquery); We will bind the toggleexpandcollapse() to the click event for all <li> elements, including the elements with nothing underneath them, also known as leaf nodes. That s because we want the leaf nodes to do something crucial absolutely nothing. Unhandled click events bubble up the DOM, so if we only attach a click observer to the <li> elements with.expanded or.collapsed classes, the click event for a leaf node would bubble up to the parent <li> element, which is one of our collapsible nodes. That means the code would trigger that node s click event, which would make it collapse suddenly and unexpectedly, and we d be liable for causing undue harm to our users fragile psyches. To prevent this Rube Goldberg styled catastrophe from happening, we call event.stoppropagation(). Adding an event handler to all <li> elements ensures the click event will never bubble up and nothing will happen, just like we expect. For more details on event propagation, read Why Not Just Return False?, on page 9. As mentioned at the beginning of the chapter, we want to give our users helper links that appear at the top of the list to toggle all of the nodes. We can create these links within jquery and prepend them to our collapsible list. Because building HTML in jquery can become verbose, we re better off moving the click event logic into separate helpers to prevent the prependtogglealllinks() functions from becoming unreadable. Download collapsiblelist/javascript.js function prependtogglealllinks() { var container = $('<div>').attr('class', 'expand_or_collapse_all'); container.append( $('<a>').attr('href', '#'). html('expand all').click(handleexpandall) ). append(' '). append( $('<a>').attr('href', '#'). html('collapse all').click(handlecollapseall) ); $('ul.collapsible').prepend(container); function handleexpandall(event) { $('ul.collapsible li.collapsed').toggleexpandcollapse(event);

8 9 Joe asks: Why Not Just Return False? In a jquery function, return false works double duty by telling the event not to bubble up the DOM tree and not to do whatever the element s default action is. This works for most events, but sometimes we want to make the distinction between stopping event propagation and preventing a default action from triggering. Or we may be in a situation where we always want prevent the default action, even if the code in our function somehow breaks. That s why at times it may make more sense to call event.stoppropagation() or event.preventdefault() explicitly rather than waiting until the end of the function to return false. a a. function handlecollapseall(event) { $('ul.collapsible li.expanded').toggleexpandcollapse(event); We can quickly create a DOM object by wrapping a string representing the element type we want, in this case an <a> tag, in a jquery element. Then we set the attributes and HTML through jquery s API. For simplicity s sake, we re going to create two links that say Expand all and Collapse all that are separated by a pipe symbol. The two links will trigger their corresponding helper functions when they re clicked. Finally, we will write an initialize function that gets called once the page is ready. This function will also hide any nodes that were not marked as.expanded and add the.collapsed class to the rest of the <li> elements. Download collapsiblelist/javascript.js function initializecollapsiblelist() { $('ul.collapsible li').click(function(event) { $(this).toggleexpandcollapse(event); ); $('ul.collapsible li:not(.expanded) > ul').hide(); $('ul.collapsible li ul'). parent(':not(.expanded)'). addclass('collapsed'); We bind the click event to all of the <li> elements that are in a.collapsible list. We also added the expand/collapse classes to all of the <li> elements, except the products themselves. These classes will help us when it comes time to style our list.

9 10 When the DOM is ready, we ll tie it all together by initializing the list and adding the Expand all Collapse all links to the page. Download collapsiblelist/javascript.js $(document).ready(function() { initializecollapsiblelist(); prependtogglealllinks(); ) Since this is a jquery plug-in, we can easily add this functionality to any list on our site by adding a.collapsible class to an unordered list. This makes the code easily reusable so that any long and cluttered list can be made easy to navigate and understand. Further Exploration If we start out by building a solid, working foundation without JavaScript, we can build upon that foundation to add in extra behavior. And if we write the JavaScript and connect the behavior into the page using CSS classes rather than adding the JavaScript directly to the HTML itself, everything is completely decoupled. This also keeps our sites from becoming too JavaScript dependent, which means more people can use your sites when JavaScript isn t available. We call this progressive enhancement, and it s an approach we strongly recommend. When building photo galleries, make each thumbnail link to a larger version of the image that opens on its own page. Then use JavaScript to intercept the click event on the image and display the full-sized image in a lightbox, and then use JavaScript to add any additional controls that are useful only when JavaScript is enabled, just like we did in this recipe. When you re building a form that inserts records and updates the values on the screen, create the form with a regular HTTP POST request first, and then intercept the form s submit event with JavaScript and do the post via Ajax. This sounds like more work, but you end up saving a lot of time; you get to leverage the form s semantic markup and use things like jquery s serialize() method to prepare the form data, rather than reading each input field and constructing your own POST request. Techniques like this are well-supported by jquery and other modern libraries because they make it easy to build simple, accessible solutions for your audience.

Extracted from: Agile Web Development with Rails 4 This PDF file contains pages extracted from Agile Web Development with Rails 4, published by the Pragmatic Bookshelf. For more information or to purchase

Extracted from: The Cucumber Book Behaviour-Driven Development for Testers and Developers This PDF file contains pages extracted from The Cucumber Book, published by the Pragmatic Bookshelf. For more information

Extracted from: icloud for Developers Automatically Sync Your ios Data, Everywhere, All the Time This PDF file contains pages extracted from icloud for Developers, published by the Pragmatic Bookshelf.

Extracted from: Real-World Kanban Do Less, Accomplish More with Lean Thinking This PDF file contains pages extracted from Real-World Kanban, published by the Pragmatic Bookshelf. For more information or

Extracted from: Stripes... and Java Web Development Is Fun Again This PDF file contains pages extracted from Stripes, published by the Pragmatic Bookshelf. For more information or to purchase a paperback

Extracted from: ipad Programming A Quick-Start Guide for iphone Developers This PDF file contains pages extracted from ipad Programming, published by the Pragmatic Bookshelf. For more information or to

jquery Tutorial for Beginners: Nothing But the Goods Not too long ago I wrote an article for Six Revisions called Getting Started with jquery that covered some important things (concept-wise) that beginning

Tutorial JavaScript: Switching panels using a radio button www.nintex.com support@nintex.com Contents About this tutorial... 3 Upload the JavaScript File... 4 Using JavaScript to hide or show a control

Developers Guide Designs and Layouts HOW TO IMPLEMENT WEBSITE DESIGNS IN DYNAMICWEB Version: 1.3 2013.10.04 English Designs and Layouts, How to implement website designs in Dynamicweb LEGAL INFORMATION

HTML5/CSS3/JavaScript Programming Description: Prerequisites: Audience: Length: This class is designed for students that have experience with basic HTML concepts that wish to learn about HTML Version 5,

How-to Guide: MIT DLC Drupal Cloud Theme This guide will show you how to take your initial Drupal Cloud site... and turn it into something more like this, using the MIT DLC Drupal Cloud theme. See this

Introduction jquery is a JavaScript library. It provides us with simple methods for achieving complex tasks. jquery s syntax allows us to side-step the intricacies of vanilla JavaScript. How jquery Works

Page Editor Recommended Practices for Developers Rev: 7 July 2014 Sitecore CMS 7 and later Page Editor Recommended Practices for Developers A Guide to Building for the Page Editor and Improving the Editor

A Hyperion White Paper Custom Javascript In Planning Creative ways to provide custom Web forms This paper describes several of the methods that can be used to tailor Hyperion Planning Web forms. Hyperion

Joomla Templates 101 Barb Ackemann Joomla Day NE May 30, 2009 NOTE: Slides, files and resources are all online So you can listen /think hard and not worry about writing everything down! Joomla Templates

EMC White Paper Introduction to XML Applications Umair Nauman Abstract: This document provides an overview of XML Applications. This is not a comprehensive guide to XML Applications and is intended for

What is JQuery JQuery is lightweight, client side JavaScript library file that supports all browsers. JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling,

WP Popup Magic User Guide Introduction Thank you so much for your purchase! We're excited to present you with the most magical popup solution for WordPress! If you have any questions, please email us at

PSU 2012 JavaScript: Advanced JavaScript: Advanced The purpose of customizing PowerSchool with JavaScript is to make it easier for people in your district to use PowerSchool based on your schools unique

Extracted from: Pragmatic Version Control using Subversion, 2nd Edition This PDF file contains pages extracted from Pragmatic Version Control, one of the Pragmatic Starter Kit series of books for project

Creating Online Surveys with Qualtrics Survey Tool Copyright 2015, Faculty and Staff Training, West Chester University. A member of the Pennsylvania State System of Higher Education. No portion of this

WINDOWS 7 & HOMEGROUP SHARING WITH WINDOWS XP, WINDOWS VISTA & OTHER OPERATING SYSTEMS Abstract The purpose of this white paper is to explain how your computers that are running previous versions of Windows

Advanced Web Development Duration: 6 Months SCOPE OF WEB DEVELOPMENT INDUSTRY Web development jobs have taken thе hot seat when it comes to career opportunities and positions as a Web developer, as every

Authoring Within a Content Management System The Content Management Story Learning Goals Understand the roots of content management Define the concept of content Describe what a content management system

Support Notes (Issue 1) September 2015 Certificate in Digital Applications (DA105) Coding for the Web IGphones Introduction Before tackling the Summative Project Brief (SPB), students should have acquired

LabVIEW Internet Toolkit User Guide Version 6.0 Contents The LabVIEW Internet Toolkit provides you with the ability to incorporate Internet capabilities into VIs. You can use LabVIEW to work with XML documents,

Triggers & Actions 10 CHAPTER Introduction Triggers and actions are the building blocks that you can use to create interactivity and custom features. Once you understand how these building blocks work,

Extracted from: Test-Drive ASP.NET MVC This PDF file contains pages extracted from Test-Drive ASP.NET MVC, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy,

Microsoft Small Business Financials Small Business Center Integration Copyright Copyright 2005 Microsoft Corporation. All rights reserved. Complying with all applicable copyright laws is the responsibility

INTRODUCTION : Web Development Techniques (Optional) This is one of the three optional courses designed for Semester 3 of the Bachelor of Information Technology Degree program. This course on web development

Extracted from: Code in the Cloud Programming Google AppEngine This PDF file contains pages extracted from Code in the Cloud, published by the Pragmatic Bookshelf. For more information or to purchase a

Instant Chime for IBM Sametime Installation Guide for Apache Tomcat and Microsoft SQL Spring 2015 Copyright and Disclaimer This document, as well as the software described in it, is furnished under license

Developing ASP.NET MVC 4 Web Applications MOC 20486 Course Outline Module 1: Exploring ASP.NET MVC 4 The goal of this module is to outline to the students the components of the Microsoft Web Technologies

Team Members: Christopher Copper Philip Eittreim Jeremiah Jekich Andrew Reisdorph Client: Brian Krzys June 17, 2014 Introduction Newmont Mining is a resource extraction company with a research and development

Advanced Online Media Dr. Cindy Royal Texas State University - San Marcos School of Journalism and Mass Communication Using JQuery to Make a Photo Slideshow This exercise was modified from the slideshow

1 of 5 3/23/2007 1:37 PM Ajax: A New Approach to Web Applications by Jesse James Garrett February 18, 2005 If anything about current interaction design can be called glamorous, it s creating Web applications.

Copyright 2011 Smart VA Ltd All Rights Reserved. No part of this guide may be reproduced or transmitted in any form whatsoever, electronic, or mechanical, including photocopying, recording, or by any informational

To ensure the functioning of the site, we use cookies. We share information about your activities on the site with our partners and Google partners: social networks and companies engaged in advertising and web analytics. For more information, see the Privacy Policy and Google Privacy &amp Terms.
Your consent to our cookies if you continue to use this website.