Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Dreamweaver Developer Center /

JavaScript for web designers

by Matt Stow

Matt Stow
  • www.mattstow.com

Content

  • What is JavaScript and the DOM?
  • Learning the basics
  • Using JavaScript
  • Refactoring for jQuery

Created

15 December 2008

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
Dreamweaver JavaScript jQuery Spry website

Requirements

Prerequisite knowledge

Familiarity with the Dreamweaver CS4 workspace and building websites using CSS and XHTML.

User level

Intermediate

Required products

  • Dreamweaver CS4 (Download trial)

Sample files

  • js_for_designers_files.zip (34 KB)

Note: This tutorial was written for Creative Suite 4. Although the screenshots may differ from what you see on your screen, the content is still valid for Creative Suite 5.

Web designer really is an ambiguous job title, isn't it? What does a web designer do exactly?

In my opinion, to be a web designer, you need to have some level of competency or awareness in all of the following interconnected areas:

  • Information architecture
  • Layout design
  • Interaction design
  • Usability
  • Accessibility
  • Standards-compliant, semantic XHTML
  • CSS
  • Browser limitations and inconsistencies
  • JavaScript
  • Server-side programming languages

By being proficient in all of these areas, you will not just end up with a web design, but a complete web solution.

A majority of designers fail, I think, when it comes to interaction design, especially client-side interaction. For some reason, JavaScript is widely ignored by designers, who believe it to be part of the developer's tool box. Sure, a developer has uses for writing JavaScript code, but those use cases differ completely from a designer's use cases.

For a designer, using JavaScript opens up a world of possibilities to improve the interaction of the design, and ultimately, the overall user-experience. This is why you, as a designer, need to embrace JavaScript, and bask in the benefits it can provide to your designs and your customers. And besides, JavaScript was designed to make it easy for non-programmers to spruce up the design of web pages.

In this article you will learn how web designers can embrace JavaScript to improve the interaction and overall user experience of their designs.

What is JavaScript and the DOM?

JavaScript is an object-oriented scripting language used for client-side web development. Despite its name, it is essentially unrelated to the Java programming language, but does provide an excellent opportunity to make web pages more interactive.

The Document Object Model (DOM) is a platform- and language-neutral interface that allows programs and scripts, such as JavaScript, to dynamically access and update the content, structure, and style of XHTML documents. The DOM represents XHTML documents as a tree structure of elements. By traversing the DOM tree with JavaScript, you can reference all XHTML elements, their attributes, and the text they contain. You can also modify or delete existing elements as well as create and insert new ones.

So why should I bother with JavaScript now?

Three reasons: The rise of the Web 2.0 era, the release of Dreamweaver CS4, and the risk of being left behind.

With Web 2.0, JavaScript-based applications have become almost ubiquitous. The increasing demand for JavaScript development has led to the creation of a number of JavaScript libraries or frameworks that allow for easier development through their pre-written controls.

Dreamweaver CS4 is geared towards creating next-generation web experiences by supporting the following new features that assist JavaScript developers:

  • Live view: This feature lets you design your web pages under real-world browser conditions while still providing direct access to the code. Changes to the code are instantly reflected in the rendered display.
  • Code hinting for Ajax and JavaScript frameworks: This feature lets you write JavaScript more quickly and accurately with improved support for JavaScript core objects and primitive data types. You can put the extended coding functionality of Dreamweaver CS4 to work by incorporating popular JavaScript frameworks, including jQuery, Prototype, and Spry.
  • Code Navigator: This features lets you see all the code sources that affect your current selection, such as CSS rules, server-side includes, external JavaScript functions, Dreamweaver templates, iframe source files, and more.
  • Related files: This feature lets you manage the various files that make up today's web pages more efficiently. Click any related file to see both its source in Code view and the parent page in Design view.

Learning the basics

Always adhere to web standards when building a site. Using web standards has the following benefits:

  • Simplified and cost-effective development and maintenance
  • Continued compatibility with current and future web browsers
  • Improved accessibility to more people and Internet devices
  • Opportunity for increased search engine rankings

I assume that you're already familiar with separating structure and content from presentation by using XHTML and external CSS. Now you also need to separate the behavior level or functionality (JavaScript). This technique is known as unobtrusive JavaScript. Unobtrusive JavaScript promotes graceful degradation, which means the documents must continue to function, and be accessible, when JavaScript is unavailable.

To learn the basics of JavaScript, you'll need to be familiar with the following:

  • Variables, used to store values or expressions
  • The Document object, represents the entire XHTML document
  • Document object methods, used to find elements in the document
  • Arithmetic operators, used to perform arithmetic between variables and values
  • Assignment operators, used to assign values to variables
  • Comparison operators, used in logical statements to determine equality or difference between variables and values.
  • Condition statements, used to perform different actions when certain criteria are met
  • For loop, used to run the same block of code a specified number of times
  • Functions, a reusable code-block that will be executed by an event, or when the function is called

This may seem like a lot to learn initially, but by stepping through a couple of examples, using JavaScript will quickly begin to feel quite easy.

Once you have grasped the basic concepts, you can then move on to using the Spry and jQuery frameworks to simplify your JavaScript development.

Using JavaScript

Before you begin, be sure to download the sample files called out in the introduction if you haven't done so already. Extract them to your hard disk, and set up a site in Dreamweaver that points to that location.

Note: Read the Setting up a Dreamweaver site section of the Dreamweaver help file for more details about defining a site.

Example 1: Improving usability by identifying links to files

The purpose of this example is to demonstrate how you can unobtrusively enhance the usability of a document, by identifying for users the type of file a link is pointing to.

In Dreamweaver CS4, open the file 1-identifying-links-to-files.html in Design view (see Figure 1).

A standard content area, which includes 5 links
Figure 1. A standard content area, which includes 5 links

Even if I had used real text (instead of placeholder text), initially a user would have no idea what file type each link is pointing to (most likely, they'd assume it's another HTML page). They may link to files that the user's computer does not support, or the user does not want to support. So how can you address this easily?

If each link had a small image or icon next to it that identified the file type, things would be easier for users. Put differently, if each link had a class that represented the link's file type, you could use CSS to add an identifying icon next to each link.

However, if this is an existing static site, you can't be expected to find every link, and add an appropriate class with each link and then upload the site again, and if it is a fully content-managed site, you can't expect the user to do it either.

By using JavaScript, you could identify which links needed an appropriate file type class, and add them automatically, potentially saving hours of work. Although adding a class in the markup would benefit all users, it's not worth the effort, when the amount of users without JavaScript is a small minority.

First you need to plan your approach:

  1. When the document has loaded, you need to find all links (<a> tags) that exist with your #content div. Specifically targeting the #content div means that links in the navigation, for example, won't be affected, and it also improves performance.
  2. Next, you need to loop through each of the links that exist and check their href value. If it contains a known file type (for example, doc, pdf, and so on), apply that file type as a class.

Too easy. So let's do it!

  1. With the file 1-identifying-links-to-files.html open in Design view in Dreamweaver, switch to Code view.
  2. Before the closing </body> tag, start a script block. All JavaScript located in the document must be in a script block:
<script type="text/javascript"> </script>
  1. Inside of this block, define a variable that contains your links:
var links = document.getElementById("content").getElementsByTagName("a");

This creates a variable called links and assigns it an array of elements whose tag is <a>, which resides within an element whose id is content, which resides within the document.

This line of code uses four of the JavaScript features I mentioned earlier, and it also showcases the new code hinting support in Dreamweaver CS4. When you press the . key a code hint will pop up (as it does when writing XHTML and CSS) to allow you to select the desired property easily, and see its usage.

  1. Next you need to loop through each link:
for (var i=0; i<links.length; i++) { }

For loops loop through a block of code a specified number of times. In this case, you set a counter (i) to 0 and increase the counter by 1 (i++) at the end of the loop block for as long as the counter is less than the length of items stored in links (i<links.length).

  1. Inside the loop, you need to check whether a link in the links collection has an appropriate href value, and set its class if necessary:
if (links[i].href.indexOf("doc") != -1) { links[i].className = "doc"; }

This if statement determines whether the link's href value (at position links[i]) contains "doc". If it does (its indexOf is not [!=] -1), it assigns a class of "doc" to the link.

  1. You then need to continue testing for the other file types: pdf, ppt, xls, and zip. For this, you use an else if for the remaining four file types:
else if (links[i].href.indexOf("pdf") != -1) { links[i].className = "pdf"; }

You should end up with the script shown in Figure 2.

The correct script structure and code
Figure 2. The correct script structure and code
  1. Save your document.

Next, use two other features new in Dreamweaver CS4.

  1. Press the Live View button above the document and behold the awesomeness! Note that I've already accounted for the file type classes in the linked style sheet (see Figure 3).
The Live view rendering of the document; now you can you tell which link points to which file.
Figure 3. The Live view rendering of the document; now you can you tell which link points to which file.

Although Live view does not replace the need to use the Preview in Browser feature (because full, cross-browser testing is always required), it greatly enhances your workflow by reducing the need to switch from Dreamweaver to the browser.

  1. Now press the Live Code button. This shows a read-only version of the code as the browser sees it, including any additions that JavaScript may have made.

    Note that each of the links in the page has also been given the appropriate class attribute as defined in the JavaScript code you wrote (see Figure 4).

Live code shows any effects of JavaScript manipulation
Figure 4. Live code shows any effects of JavaScript manipulation

As you are not familiar with my style sheet, you can use the new Code Navigator to quickly find the correct styles.

  1. Either in Live view or Live code, hover over one of the links and press Alt (Windows) or Option+Cmd (Mac), and click to bring up the Code Navigator. Hover over the CSS selectors to see their associated rules, and click to be taken to that location within the style sheet (see Figure 5).

    Note: Doing so will turn off Live code.

The Code Navigator displays the CSS rules that are relevant to the inspected object.
Figure 5. The Code Navigator displays the CSS rules that are relevant to the inspected object.

Using unobtrusive code

This is a great start in using JavaScript to improve a user's interaction with your document. However, the code is not unobtrusive because it resides within the body of the document.

Once again, the Dreamweaver team has thought of a solution:

  1. Turn off Live view and switch to Code view to look at your HTML file. This makes it easier for you to see what happens.
  2. From the Commands menu, select Externalize JavasScript.
  3. In the dialog box that appears, keep the options Externalize JavaScript and attach unobtrusively, select the Remove JavaScript from body check box and press OK.

    You will be prompted with an info dialog box that describes what has happened (see Figure 6).

Result of externalizing JavaScript.
Figure 6. Result of externalizing JavaScript.

You'll notice that two <script> tags have been added to the head of your document: SpryDOMUtils.js, and another based on your XHTML file's name. Also, the <script> tag at the end of your document is no longer there.

  1. Save your document, which will copy the SpryDOMUtils.js file to your local site, and notify you of this fact.

    By using another new feature in Dreamweaver CS4, the Related Files bar, you can quickly see and access the document's related files, while still remaining in context with the original document (see Figure 7). This is very useful for making modifications to style sheets and JavaScript (JS) files while previewing a document in Live view.

The Related Files bar shows the external files that are referenced by the document.
Figure 7. The Related Files bar shows the external files that are referenced by the document.
  1. From the Related Files bar, open the file 1-identifying-links-to-files.js.

In it, you'll see your existing JavaScript but it has been wrapped in a Spry.Utils.addLoadListener(function() {} statement (see Figure 7).

The contents of 1-identifying-links-to-files.js
Figure 8. The contents of 1-identifying-links-to-files.js

What this does is reference the Spry DOM Utils library that has been included in the document to automatically perform the link identification when the document has loaded, so it's now totally unobtrusive.

There is a downside to attaching JS files on load of the document, however. On load means when everything has loaded, including all images declared via <img> tags and as backgrounds in CSS. So, on large pages, and pages with lots of images, it may take some time before the script is executed, and the user could theoretically already be reading the content while the link file type images are added, which may not make for a great user experience.

Refactoring for jQuery

Another popular JavaScript framework, jQuery, sets out to address this issue by allowing scripts to execute when the DOM is ready, not when everything has loaded. This can greatly reduce the length of time required, resulting in a better user experience.

  1. Return to the Code view of the 1-identifying-links-to-files.html file.
  2. Click in the src="SpryAssets/SpryDOMUtils.js" and press Ctrl+Space to open the Browse hint. Press Enter, and with the dialog box, select the jquery-1.2.6.min.js file, which is included in the js folder.
  3. Save your document and press F5 to refresh. Note that the Related Files bar instantly updates the reference to this file.
  4. Return to edit the file 1-identifying-links-to-files.js.
  5. Replace Spry.Utils.addLoadListener(function() { with $(document).ready(function() {
  6. Save your document and return to Live view. Note that the link identification still works exactly as it did before. All you've done is replace the method in which the code is called, by using the ready event, to something more efficient.

You could leave it at that, but then you would be missing out on the benefits of using jQuery. jQuery is designed to change the way that you write JavaScript; to make your work/life a lot easier.

Two major features of jQuery are that elements can be referenced using a familiar CSS selector syntax, and its functions are chainable, so you can perform multiple operations in one go.

The JavaScript code in your document could quite easily be replaced with this:

$("#content a[href$=doc]").addClass("doc"); $("#content a[href$=pdf]").addClass("pdf"); $("#content a[href$=ppt]").addClass("ppt"); $("#content a[href$=xls]").addClass("xls"); $("#content a[href$=zip]").addClass("zip");

Amazingly simple, isn't it?

Let me explain what's happening. $("#content a[href$=doc]") is a jQuery selector. In this case it selects all <a> elements whose href value ends with "doc", and that reside within the #content element. $ is an alias for the jQuery class, therefore $() constructs a new jQuery object. The addClass function called next is a method of the jQuery object.

Why is this better than your existing method?

  • It's a lot smaller, neater, and easier to understand.
  • The addClass function takes into consideration whether the link already has a class, and just appends the new one. Your earlier attempt would overwrite any existing class, although this is easy to cater for.
  • The $ in href$=doc matches elements that have the specified attribute and the attribute ends with the specified value. This could have been done in the original code, but would require some knowledge of regular expressions in the existing example.

Improved JavaScript code hinting in Dreamweaver also extrapolates the objects and methods available from a linked file, so it is not just limited to its built-in knowledge. This means that when writing jQuery, you can have the options available to you by pressing Ctrl+Space.

Unfortunately, a limitation is that code hinting doesn't work when working in a separate related file, like the file 1-identifying-links-to-files.js.

As code hinting is a great way to learn what's available to use, I'd suggest you continue to write your JavaScript code in the main, source XHTML, and externalize it when finished. Instead of writing it at the end of the <body> element, you can now do it within the <head> section, as long as it's below the reference to include the jQuery library.

Example 2: Drop-down navigation

A common misuse of the <select> element is to use it for navigation; whereby selecting an option would instantly take you to a new page.

However, abusing a <select> element like this is wrong for so many reasons. With semantic markup and unobtrusive JavaScript you could do something similar, but with an unordered list of links.

Here's how it works:

  • The markup is very simple; it's just a div that includes a heading and an unordered list of links.
  • The unordered list is styled to be perfectly usable without JavaScript available.
  • If JavaScript is available, a class is given to the <html> element, which in turn immediately hides the <ul> list.
  • jQuery is then used to insert a link that reads Select a Product.
  • When clicking this link, the <ul> list is made visible again, and is positioned absolutely so it comes out of the flow of its container.
  • When mousing over the <ul> list, it remains visible so users can click the links.
  • When mousing out, the <ul> list is hidden again.

It really is very simple, but quite effective. And unlike a <select> element, can be styled to your needs, and is perfectly accessible and usable to all.

Open the file 2-drop-down-list.html and its related files, which are included in the sample download files that accompany this article, to dissect and explore how this works (see Figure 9). Use the new features available in Dreamweaver CS4: Live view (including Disable JavaScript), Live code, Code Navigator and related links to assist you.

From unstyled markup to finished article; a perfectly valid, accessible, and unobtrusive drop-down list.
Figure 9. From unstyled markup to finished article; a perfectly valid, accessible, and unobtrusive drop-down list.

Where to go from here

Now that you have some knowledge of JavaScript, Spry, and jQuery, I hope that you will continue to research and learn more about their usage and benefits.

jQuery is my personal favorite JavaScript framework; however, Spry has some excellent features, too. I suggest you visit the official sites for both Spry and jQuery to gain a better understanding of them both, and then enjoy the creative opportunities made available to you as a JavaScript-savvy designer!

More Like This

  • Integrating Flash content with the HTML environment
  • Understanding cascading style sheets
  • Customizable starter designs for beginners
  • CSS page layout basics
  • Applying design to Spry widgets
  • Managing websites with multiple layouts
  • Building a photo album with the Spry framework
  • Checking for cross-browser CSS rendering issues
  • Understanding inheritance
  • Creating dynamic tables with the Spry framework

Tutorials and samples

Tutorials

  • Understanding HTML5 semantics: Changed and absent elements
  • Mobile app with PhoneGap: Submitting to the Apple App Store
  • PhoneGap and Dreamweaver: Releasing on iOS
  • Mobile app with PhoneGap: Creating a release build for Android

Samples

  • Responsive design with jQuery marquee
  • Customizable starter design for jQuery Mobile
  • Customizable starter design for HTML5 video
  • Customizable starter design for multiscreen development

Dreamweaver user forum

More
04/23/2012 Resolution/Compatibility/liquid layout
04/20/2012 using local/testing server with cs5 inserting images look fine in the split screen but do not show
04/18/2012 Ap Div help
04/23/2012 Updating

Dreamweaver Cookbook

More
11/07/2011 Simple social networking share buttons
09/20/2011 Registration form that will generate email for registrant to validate
08/21/2011 Spry Accordion - Vertical Text - Auto Start on Page Load - Mouse Over Pause
08/17/2011 Using cfdump anywhere you like

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement