Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Javascript

  • submit to reddit

Getting Started with JavaFX

By Stephen Chin

17,509 Downloads · Refcard 56 of 151 (see them all)

Download
FREE PDF


The Essential JavaFX Cheat Sheet

JavaFX makes it easier to build better RIAs with graphics, animation, and media. Built on Java, this platform uses existing Java libraries and is capable of running in your browser, on your desktop, and on your phone. This DZone Refcard is ideal for the beginner, and will help you get started programming with JavaFX Script. It will also serve as a convenient reference once you have mastered the language. The instructions in this Refcard assume that you are using an IDE, but it is also possible to do everything from the command line as well.
HTML Preview
JavaFX

Getting Started with JavaFX

By Stephen Chin

About JavaFX

JavaFX is an exciting new platform for building Rich Internet Applications with graphics, animation, and media. It is built on Java technology, so it is interoperable with existing Java libraries, and is designed to be portable across different embedded devices including mobile phones and set-top boxes. This Refcard will help you get started programming with JavaFX Script and also serve as a convenient reference once you have mastered the language.

To get started, you will have to download the latest JavaFX SDK from the JavaFX website here: http://javafx.com/.

The instructions in the following tutorial assume that you are using an IDE, such as NetBeans. However, it is possible to do everything from the command line as well.

JFXPoetry, a si mple exa mple

To illustrate how easy it is to build an application that melds graphics, text, animation, and media, we will start with a simple tutorial. The goal will be to write an application that:

  • Loads and displays an image from the internet
  • Displays and animates a verse of poetry
  • Declaratively mixes in graphic effects
  • Plays media asynchronously

For the JFXPoetry theme, we will use “Pippa’s Song,” a wellknown excerpt from Robert Browning’s Pippa Passes.

Loading an Image on the Stage

Stage and Scene are the building blocks of almost every JavaFX program. A Stage can either be represented as a Frame for desktop applications, a rectangle for applets, or the entire screen for mobile devices. The visual content of a Stage is called a Scene, which contains a sequence of content Nodes that will be displayed in stacked order. The following program creates a basic Stage and Scene which is used to display an image:


var scene:Scene;
Stage {
  title: “Pippa’s Song by Robert Browning”
  scene: scene = Scene {
    content: [
      ImageView {
        image: bind Image {
	 height: scene.height
	 preserveRatio: true
	 url: “http://farm1.static.flickr.com/39/
	    121693644_75491b23b0.jpg”
        }
      }
    ]
  }
}

Notice that that JavaFX syntax makes it simple to express nested UI structures. The curly braces “{}” are used for object instantiation, and allow inline initialization of variables where the value follows the colon “:”. This is used to instantiate an ImageView with an Image inside that loads its content from the given URL. To ensure the image resizes with the window, we set preserveRatio to true and bind the Image. Binding is a very powerful facility in JavaFX that makes it easy to update values without heavyweight event handlers. Compiling and running this application will display a picture of a misty morning in Burns Lake, BC, Canada taken by Duane Conlon as shown in Figure 1.1 2

Figure 1.1 2

Figure 1: A JavaFX Stage containing an image loaded from the network

Displaying Text With Effects

Displaying text in JavaFX is as simple as instantiating a Text Node and setting the content to a String. There are many variables available on Text, but for this example we will set the font, fill color, and also add a Drop Shadow effect to make the text stand out on the background.


1 Creative Commons Attribution 2.0 License: http://creativecommons.org/licenses/by/2.0/

2 Duane Conlon’s Photostream: http://www.flickr.com/photos/duaneconlon/


var text:Text;
Stage {
	  ...
	  ImageView {
        ...
	  },
	  text = Text {
		effect: DropShadow {}
		font: bind Font.font(“Serif”, FontWeight.BOLD,
					  scene.height / 12.5)
	    fill: Color.GOLDENROD
	    x: 10
	    y: bind scene.height / 6
	    content: “The year’s at the spring,\n”
				 “And day’s at the morn;\n”
				 “Morning’s at seven;\n”
				 “The hill-side’s dew-pearled;\n”
				 “The lark’s on the wing;\n”
				 “The snail’s on the thorn;\n”
				 “God’s in His heaven--\n”
				 “All’s right with the world!”
        }

Notice that rather than specifying the whole poem text on one line we have split it across several lines, which will automatically get concatenated. Also, we have used the bind operator to set both the font size and y offset, which will update their values automatically when the scene height changes. Figure 2 shows the updated example with text overlaid on the Image.

Figure 2

Figure 2: Updated example with a Text overlay

JavaFX offers a large set of graphics effects that you can easily apply to Nodes to create rich visual effects. Table 1 lists all the available effects you can choose from.

Table 1. Graphics effects available in JavaFX

Effect Description
Blend Blends two inputs together using a pre-defined BlendMode
Bloom Makes brighter portions of the Node appear to glow
BoxBlur Fast blur with a configurable quality threshold
ColorAdjust Per-pixel adjustments of hue, saturation, brightness, and contrast
DisplacementMap Shifts each pixel by the amount specified in a DisplacementMap
DropShadow Displays an offset shadow underneath the node
Flood Fills a rectangular region with the given Color
GaussianBlur Blurs the Node with a configurable radius
Glow Makes the Node appear to glow with a given intensity level
Identity Passes an image through to a chained effect
InnerShadow Draws a shadow on the inner edges of the Node
InvertMask Returns a mask that is the inverse of the input
Lighting Simulates a light source to give Nodes a 3D effect
MotionBlur Blurs the image at a given angle to create a motion effect
PerspectiveTransform Maps a Node to an arbitrary quadrilateral for a perspective effect
Reflection Displays an inverted view of the Node to create a reflected effect
SepiaTone Creates a sepia tone effect to mimic aged photographs
Shadow Similar to a DropShadow, but without the overlaid image

Animated Transitions

Animations in JavaFX can be accomplished either by setting up a Timeline from scratch, or using one of the pre-fabricated Transitions. To animate the Text rising onto the screen, we will use a TranslateTransition, which adjusts the position of a Node in a straight line for the specified duration:


var animation = TranslateTransition {
  duration: 24s
  node: text
  fromY: scene.height
  toY: 0
  interpolator: Interpolator.EASEOUT
}
animation.play();

By setting an interpolator of EASEOUT, the text will start at full speed and gradually deaccelerate as it approaches its destination. Animations and Transitions can also be configured to repeat, run at a specific rate, or reverse. To run the transition, all you need to do is call the play() function, which will animate the text as shown in Figure 3.

Figure 3

Figure 3: Animated Text Scrolling Into View

Table 2 lists all of the available transitions that are part of the JavaFX API. To get a feel for how the different transitions work, try adding a FadeTransition that will gradually fade the background in over a 5 second duration.

Table 2. Transitions Supported by JavaFX

Transition Description
FadeTransition Changes the opacity of a node over time
ParallelTransition Plays a sequence of transitions in parallel
PathTransition Animates nodes along a Shape or Path
PauseTransition Executes an action after the specified delay
RotateTransition Changes the rotation of a node over time
ScaleTransition Changes the size of a node over time
SequentialTransition Plays a sequence of transitions in series
TranslateTransition Changes the position of a node over time

Interacting With Controls

The JavaFX 1.2 release features a new library of skinnable controls written in pure JavaFX. Table 3 lists some of the new controls and what they can be used for.

Table 3. Controls Available in JavaFX 1.2

Control Description
Button Button that can contain graphics and text
CheckBox Selectable box that can be checked, unchecked, or undefined
Hyperlink HTML-like clickable text link
Label Text that can be associated with anther control
ListView Scrollable list that can contain text or Nodes
ProgressBar Progress bar that can show percentage complete or be indeterminate
RadioButton Selectable button that can belong to a group
ScrollBar Scroll control typically used for paging
Slider Draggable selector of a number or percent
TextBox Text input control

The simplest control to use is a Button, which can easily be scripted to play the animation sequence again from the beginning.


var button:Button;
Stage {
...
text = Text {
...
    },
    button = Button {
        translateX: bind (scene.width - button.width) / 2
        translateY: bind (scene.height - button.height) / 2
        text: “Play Again”
      visible: bind not animation.running
      action: function() {
        animation.playFromStart();
      }
    }
  ]

Ths bind operator is used to both hide the button while the animation is playing and also center the button in the window. Initially the button is invisible, but we added a new SequentialTransition that plays a FadeTransition to show the button after the translation is complete. Clicking the button shown in Figure 4 will hide it and play the animation from the beginning.

Figure 4

Figure 4: Button Control to Play the Animation Again

Panning With Layouts

JavaFX 1.2 comes with several new layouts that make it easy to design complex UIs. One of these is the ClipView, which we will use to support dragging of the poem text. ClipView takes a single Node as the input and allows the content to be panned using the mouse:


 content: [
...
    ClipView {
	 width: bind scene.width
	 height: bind scene.height
	 override var maxClipX = 0
	 node: text = Text {
...
     }
   }

To ensue the ClipView takes the full window, its width and height are bound to the scene. Also, we have overridden the maxClipX variable with a value of 0 to restrict panning to the vertical direction. The text can now be dragged using the mouse as shown in Figure 5.

Figure 5

Figure 5: Panning the Text using a ClipView

Table 4 lists all of the available layouts that come JavaFX comes with. HBox and VBox have been around since the 1.0 release, but all the other layouts are new in JavaFX 1.2.

Table 4. Layouts Available in JavaFX 1.2

Layout Description
HBox Lays out its contents in a single, horizontal row
VBox Lays out its contents in a single, vertical column
ClipView Clips its content Node to the bounds, optionally allowing panning
Flow Lays out its contents either vertically or horizontally with wrapping
Stack Layers its contents on top of each other from back to front
Tile Arranges its contents in a grid of evenly sized tiles

Finishing with Media

JavaFX has built-in media classes that make it very simple to play audio or video either from the local files or streaming off the network. To complete the example we will add in a public domain clip of Indigo Bunting birds chirping in the background. Adding in the audio is as simple as appending a MediaPlayer with autoPlay set to true that contains a Media object pointing to the URL.


MediaPlayer {
  autoPlay: true
  media: Media {
    source: “http://video.fws.gov/sounds/35indigobunting.mp3”
  }
}

In this example we are using an mp3 file, which is supported across platforms by JavaFX. Table 5 lists some of the common media formats supported by JavaFX, including all the crossplatform formats.

Table 5. Common Media Formats Supported by JavaFX

Type Platform Format File Extension
Audio Cross-platform MPEG-1 Audio Layer 3 mp3
Audio Cross-platform Waveform Audio Format wav
Audio Macintosh Advanced Audio Coding m4a, aac
Audio Macintosh Audio Interchange File Format aif, aiff
Video Platform Format File Extension
Video Cross-platform Flash Video flv, f4v
Video Cross-platform JavaFX Multimedia fxm
Video Windows Windows Media Video wmv, avi
Video Macintosh QuickTime mov
Video Macintosh MPEG-4 mp4

To try the completed example complete with animation and audio, you can click on the following url:

http://jfxtras.org/samples/jfxpoetry/JFXPoetry.jnlp

The full source code for this application is available on the JFXtras Samples website: http://jfxtras.org/portal/samples

Running on Mobile

To run the sample in the Mobile Emulator all you have to do is pass in the MOBILE profile to the javafxpackager program or switch the run mode in your IDE project properties. JavaFX Mobile applications are restricted to the Common Profile, which does not include all the features of desktop applications. The full list of restrictions is shown in Table 5.

Table 5. Functionality Not Available in the Common Profile

Class(es) Affected Variables and Methods
javafx.ext.swing.* All
javafx.reflect.* All
javafx.scene.Node effect, style
javafx.scene.Scene stylesheets
javafx.scene.effect.* All
javafx.scene.effect.light.* All
javafx.scene.shape.ShapeIntersect All
javafx.scene.shape.ShapeSubtract All
javafx.scene.text.Font autoKern, embolden, letterSpacing, ligatures, oblique, position
javafx.stage.AppletStageExtension All
javafx.util.FXEvaluator All
javafx.util.StringLocalizer All

Over 80% of the JavaFX API is represented in the Common Profile, so it is not hard to build applications that are portable. In this example we used a DropShadow on the text that, once removed, will let us run the example in the Mobile Emulator as shown in Figure 6.

Figure 6

Figure 6: JFXPoetry application running in the Mobile Emulator

Running as a Desktop Widget

You can deploy your application as a desktop widget using the WidgetFX open-source framework. Any JavaFX application can be converted to a widget by including the WidgetFX-API.jar and making some small updates to the code.

The Following code fragment highlights the code changes required:


var widget:Widget = Widget {
  resizable: false
  width: 500
  height: 375
  content: [
...
      height: widget.height
...
    font: bind Font.font(“Serif”, FontWeight.BOLD,
              widget.height / 12.5)
...
    y: bind widget.height / 6
...
  ]
}


...
    fromY: widget.height
...
widget;

The updates to the code include the following three changes:

  • Wrap your application in a Widget class. The Widget class extends javafx.scene.layout.Panel, which makes it easy to extend.
  • Set the initial widget width/height and modify references from scene to widget.
  • Return the widget at the end of the script.

To run the widget, simply change your project properties to run the application using Web Start Excecution. This will automatically create a JNLP file compatible with WidgetFX and launch the Widget Runner, which allows you to test your widget as shown in the Figure 7.

Figure 7

Figure 7: JFXPoetry running as a desktop widget

For more information about WidgetFX, including SDK download, documentation, and additional tutorials, check out the project website: http://widgetfx.org/

JavaFX Reference

Language Reference

JavaFX supports all the Java datatypes plus a new Duration type that simplifies writing animationed UIs.

Data Types:

DataType Java Equivalent Range Examples
Boolean boolean true or false true,false
Integer int -2147483648 to 2147483647 2009, 03731, 0x07d9
Number float 1.40×10 45 and 3.40×1038 3.14, 3e8, 1.380E-23
String String N/A “java’s”, ‘in”side”er’
Duration <None> -263 to 263-1 milliseconds 1h, 5m, 30s, 500ms
Character char 0 to 65535 0,20,32
Byte byte -128 to 127 -5, 0,5
Short short -32768 to 32767 -300, 0, 521
Long long -263 to 263-1 2009, 03731,0x07d9
Float float 1.40x10 45 and 3.40x1038 3.14, 3e8, 1.380E-23
Double double 4.94x10 324 and 1.80x10308 3.14, 3e8, 1.380E-123

JavaFX Characters cannot accept literals like ‘a’ or ‘0’, because they are treated as Strings. The primary way of getting Characters will be by calling a Java API that returns a char primitive, although you can create a new character by assigning a numeric constant

Operators:

The following table lists all the mathematical, conditional, and boolean operators along with their precedence (1 being the highest).

Operator Meaning Precedence Examples
++ Pre/post increment 1 ++i, i++
-- Pre/post decrement 1 --i, i--
not Boolean negation 2 not (cond)
* Multiply 3 2 * 5, 1h * 4
/ Divide 3 9 / 3, 1m / 3
mod Modulo 3 20 mod 3
+ Add 4 0 + 2, 1m + 20s
- Subtract (or negate) 4 (2) -2, 32 - 3, 1h - 5m
== Equal 5 value1 == value2, 4 == 4
!= Not equal 5 value1 != value2, 5 != 4
< Less than 5 value1 < value2, 4 < 5
<= Less than or equal 5 value1 <= value2, 5 <= 5
< Greater than 5 value1 > value2, 6 > 5
>= Greater than or equal 5 value1 >= value2, 6 >= 6
instanceof Is instance of class 6 node instanceof Text
as Typecast to class 6 node as Text
and Boolean and 7 cond1 and cond2
or Boolean or 8 cond1 or cond2
+= Add and assign 9 value += 5
-= Subtract and assign 9 value -= 3
*= Multiply and assign 9 value *= 2
/= Divide and assign 9 value /=4
= Assign 9 value = 7
  • Multiplication and division of two durations is allowed, but not meaningful
  • Underflows/Overflows will fail silently, producing inaccurate results
  • Divide by zero will throw a runtime exception

Sequences:

JavaFX sequences provide a powerful resizable and bindable list capability under a simple array-like syntax. All of the sequence operators (sizeof, reverse, indexof) have a relative precedence of 2.

Operation Syntax Examples
Construct

[x,y,z]
[y..z]
[y..<z]
[y..z step w]


var nums = [1, 2, 3, 4]; var letters = [“a”, “b”, “c”];
[1..5] = [1, 2, 3, 4, 5]
[1..>5] = [1, 2, 3, 4]
[1..9 step 2] = [1, 3, 5, 7, 9]

Size sizeof seq sizeof nums; // = 4
Index indexof variable

for(x in seq) {
indexof x;
}

Element seq[i] letters[2]; // = “c”
Slice

eq[x..y]
seq[x..<y]


nums[1..2]; // = [2, 3]
letters[0..<2]; // = [“a”, “b”]

Predicate seq[x|boolean] nums[n|n mod 2 == 0]; // = [2, 4]
Reverse reverse seq reverse letters; // = [“c”, “b”, “a”]
Insert

insert x into seq
insert x before seq[i]
insert x after seq[i]


insert 5 into nums; // = [1, 2, 3, 4, 5]
insert “gamma” before letters[2]; // = [“a”, “b”,
“gamma”, “c”]
insert “2.3” after nums[1]; // = [1, 2, 2.3, 3, 4]

Delete

delete seq[i]
delete seq[x..y]
delete x from seq
delete seq


delete letters[1]; // = [“a”, “c”]
delete nums[1..2]; // = [1, 4]
delete “c” from letters; // = [“a”, “b”]
delete letters; // = []

  • The javafx.util.Sequences class provides additional functions, which allow you to manipulate sequences, such as min, max, search, shuffle, and short.
  • Nested sequences are automatically flattened, so [[1,2], [3,4]] is equivalent to [1,2,3,4].
  • Sequences require commas after all elements except close braces; however it is recommended to always use commas
  • You can declare a sequence as a nativearray. This is an optimization so that arrays returned from a Java method don’t need to be converted to a sequence.

Access Modifiers:

The JavaFX access modifiers are based upon Java with the addition of extra variable-only modifiers.

Modifier Name Description
<Default> Script only access Only accessible within the same script file
package Package access Only accessible within the same package
protected Protected access Only accessible within the same package or by subclasses
public Public access Can be accessed anywhere
publicread

Read access
modifier

Var/def modifier to allow a variable to be read anywhere
public-init Init access modifier Var/def modifier to allow a variable to be initialized or read anywhere
  • Unlike Java the default permission in JavaFX is script-only rather than package.
  • The var/def access modifiers can be stacked with other modifiers, such as public-read protected

Expressions:

JavaFX supports many of the same expressions as Java, but adds in powerful inline functions and for loop extensions.

Expression Syntax Example
if

if (cond) expr1 else expr2
if (cond) then expr1 else expr2


if (grass.green) {
  grass.mow();
} else {
  grass.water();
}
var water = if (grass.color ==
BLACK) aLot else aLittle;

for

for (x in seq) expr
for (x in seq where cond) expr
for (x in seq, y in x) expr


var loans = for (b in borrowers
where b.pulse > 0)
{
  b.createLoan();
}
for (loan in loans) {
  loan.approve();
}

while while (bool) expr

while (swimming) {
  paddle();
  breathe();
}


try/catch/
finally


try {expr1} catch(exception)
{expr2} finally {expr3}


try {
  Bailout();
} catch(e:FinancialCrisis) {
  massiveBailout();
} finally {
  increaseTaxes();
}

function function(params):returnType{}

function(e:MouseEvent):Void {
     e.source.toFront();
}

Just like in Java programs:

  • continue can be used to skip a for or while loop iteration
  • break can be used to exit a for or while loop
  • return can be used to exite from a function event if inside a loop

Magic Variables:

JavaFX provides some built-in variables that can be accessed from any code running inside a script.

Name Description
__DIR__ Directory the current classfile is contained in
__FILE__ Full path to the current classfile
__PROFILE__ The current profile, which can be ‘desktop’ or ‘mobile’

API Reference

In the short span of a few pages you have already seen quite a bit of the JavaFX platform. Some other functionality that JavaFX offers includes:

Package Description
javafx.animation Animation and Interpolation
javafx.async Asynchronous Tasks and Futures
javafx.data.feed RSS/Atom Feed support
javafx.data.pull XML and JSON Pull Parsers
javafx.ext.swing Additional Swing-based Widgets
javafx.fxd Production Suite (FXD)
javafx.io Local Data Storage
javafx.reflect JavaFX Reflection Classes
javafx.chart Charting and Graphing
javafx.scene.media Media (Audio and Video) Playback
javafx.scene.shape Vector Shapes

An easy way to view and navigate the full JavaFX API is using the JFXplorer application. The following URL will launch it in as a web start application that you can use to start exploring the JavaFX API today:

http://jfxtras.org/samples/jfxplorer/JFXplorer.jnlp

Additional Resources

About The Author

Photo of Stephen Chin

Open-Source Developer and Agile Manager, Stephen Chin is founder of numerous opensource projects including WidgetFX and JFXtras and Senior Manager at Inovis in Emeryville, CA. He has been working with Java desktop and enterprise technologies for over a decade, and has a passion for improving development technologies and process. Stephen’s interest in Java technologies has lead him to start a Java and JavaFX focused blog and coauthor the upcoming Pro JavaFX Platform book together with Jim Weaver, Weiqi Gao, and Dean Iverson.

Stephen’s Blog:

http://steveonjava.com/

Jim Weaver’s JavaFX Learning Blog:

http://learnjavafx.typepad.com/

Recommended Book

ProJavaFX

Learn from bestselling JavaFX author Jim Weaver and expert JavaFX developers Weiqi Gao, Stephen Chin, and Dean Iverson to discover the highly anticipated JavaFX technology and platform that enables developers and designers to create RIAs that can run across diverse devices. Covering the JavaFX Script language, JavaFX Mobile, and development tools, Pro JavaFX™ Platform: Script, Desktop and Mobile RIA with Java™ Technology provides code examples that cover virtually every language and API feature.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

HTML5 Canvas

A Web Standard for Dynamic Graphics

By Simon Sarris

14,987 Downloads · Refcard 151 of 151 (see them all)

Download
FREE PDF


The Essential HTML5 Canvas Cheat Sheet

The HTML5 Canvas Element is perhaps the most exciting web standard that has emerged in the last few years.  It allows on-the-fly creation of graphs, diagrams, games, and other visual elements and interactive media that previously would have been impossible to construct without a plugin like Flash.  This Refcard will empower you with the tools and knowledge you need to start building with the next generation of dynamic graphic web standards.
HTML Preview
Java Enterprise Edition 6 The Most Elegant Enterprise Java Yet

HTML5 Canvas

By Simon Sarris

introduction to canvas

The HTML <canvas> element allows for on-the-fly creation of graphs, diagrams, games, and other visual elements and interactive media. It also allows for the rendering of 2D and 3D shapes and images, typically via JavaScript.

<canvas id="canvas1" width="500" height="500">
<script type="text/javascript">
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

ctx.fillText("Hello World!", 50, 50);
</script>

Canvas is perhaps the most visible part of the new HTML5 feature set, with new demos, projects, and proofs of concept appearing daily.

Canvas is a very low-level drawing surface with commands for making lines, curves, rectangles, gradients and clipping regions built in. There is very little else in the way of graphics drawing, which allows programmers to create their own methods for several basic drawing functions such as blurring, tweening, and animation. Even drawing a dotted line is something that must be done by the programmer from scratch.

Canvas is an immediate drawing surface and has no scene graph. This means that once an image or shape is drawn to it, neither the Canvas nor its drawing context have any knowledge of what was just drawn.

For instance, to draw a line and have it move around, you need to do much more than simply change the points of the line. You must clear the Canvas (or part of it) and redraw the line with the new points. This contrasts greatly with SVG, where you would simply give the line a new position and be done with it.

Browser Support and Hardware Acceleration

Canvas is supported by Firefox 1.5 and later; Opera 9 and later; and newer versions of Safari, Chrome, and Internet Explorer 9 and 10.

The latest versions of these browsers support nearly all abilities of the Canvas element. A notable exception is drawFocusRing, which no browser supports effects.

Hardware acceleration is supported in some variation by all current browsers, though the performance gains differ. It is difficult to benchmark between the modern browsers because they are changing frequently, but so far IE9 seems to consistently get the most out of having a good GPU. On a machine with a good video card it is almost always the fastest at rendering massive amounts of images or canvas-to-canvas draws.

Accelerated IE9 also renders fillRect more than twice as fast as the other major browsers, allowing for impressive 2D particle effects [1]. Chrome often has the fastest path rendering but can be inconsistent between releases. All browsers render images and rects much faster than paths or text, so it is best to use images and rects if you can regardless of which browsers you are targeting.

  Canvas SVG
Support • All modern versions of Chrome, Safari, Firefox, and Opera have at least some support. Internet Explorer 9+ has support. Almost all modern smart phones.
• Internet Explorer 7 and 8 have limited support through the excanvas library.
• Rapidly growing in popularity
• SVG support in all modern browsers. Almost all modern smart phones.
Statefulness • Bitmapped, immediate drawing surface
• Shapes are drawn and nothing is remembered about their state.
• Vector-based, retained drawing surface
• Every drawn shape is a DOM object.
Other Considerations • Generally faster
• All event handling and statefulness must be programmed yourself.
• Canvas will be effectively disabled (rendering nothing) if scripting is disabled.
• Generally slower, especially past 10,000 objects.
• Since all SVG elements are DOM objects, statefulness is built in and event handling is much easier.
• Easier for a designer to work with, many programs such as Illustrator can output SVG
• SVG has built-in support for animation.
Accessibility • Difficult to interface with other DOM objects
• Working with text can be difficult.
• Recreating text-based DOM element functionality is strongly advised against, even in the specification itself.
• Cannot operate when scripting is disabled.
• All SVG objects are already DOM objects.
• Text is searchable by the browser and web crawlers.
Best suited for • Games, fast graphics
• Very large amounts of objects
• Creating high-performance content
• Accessibility oriented content or text-oriented content
• Easily scalable shapes
• Charts, graphs, and other mostly static data displays
• Creating interactive content quickly.
What Canvas Can and Cannot Do

The specification advises against using Canvas to render static content. There are many reasons to not use Canvas if typical image and text elements will suffice. If scripting is disabled on the client, the Canvas will be useless. Text drawn on Canvas is not selectable, searchable, or crawlable by web spiders. For the same reason, Canvas makes web accessibility more difficult. If you are looking to simply stylize text or round off the edges of a text area, you should see if the desired effects (such as shadows or rounded corners) are possible with CSS3 before opting to use a Canvas.

As of August 2011, Canvas does not look the same on all browsers. The implementations of anti-aliasing (or not) differ, and other quirks can cause gradients, text, and scaled objects to look dissimilar. For instance, until a few months ago, Chrome's handling of gradients would disregard opacity and take the last-known non-gradient color's opacity instead! Both the specification and implementations of Canvas should be considered slightly, yet constantly, evolving.

A Comparison with SVG

Canvas is a very flexible drawing surface but may not be appropriate for all projects. Most immediately relevant when planning a web-app is browser support. Internet Explorer 7 and 8 only support Canvas through the excanvas library. Excanvas performance degrades very quickly with animation, so any animated web-apps that must target Internet Explorer 7 and 8 should not use canvas. Note that excanvas is also no longer under active development.

The other large difference is the statefulness of each. Canvas is an immediate drawing surface whereas SVG is retained, meaning that the DOM remembers every drawn SVG element and each element has a fully-defined DOM object associated with it, event handlers included. This makes implementing interactivity with SVG much easier than Canvas, but it also introduces a large amount of overhead that is unsuitable for performance-needing applications.

The bottom line is that SVG is easier to program for from the get-go, but Canvas is more powerful. The decision to use either should rest upon what platforms you are targeting, how much performance will be needed, what libraries you wish to use, and ease of development based on your (team's) current knowledge and skillset.

For an in-depth comparison, see the IE team's blog post: http://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspx

Canvas Performance

While the low-level of Canvas might make development slower, it outshines the other options when performance is crucial, especially when there are tens of thousands of objects to load and draw. While having each SVG object be a DOM object makes events and object modification easier to code, the overhead involved makes SVG unsuitable for complex, interactive apps. Creating 10,000 shapes in Canvas is a very fast process, while creating the same shapes in SVG means creating tens of thousands of SVG DOM nodes, resulting in a much slower process.

Canvas can be very fast, but it is up to the programmer to keep it that way. Many of the optimizations that might be taken care of by more advanced drawing frameworks must be done by the programmer. Speed becomes important, and any serious Canvas developer should familiarize himself with the typical concepts of graphics performance, such as invalidations and viewports.

Additionally, different drawing operations are faster or slower than others, and different methods of accomplishing the same task can take wildly different times. I will go over a few of them in the final section.

Creating a Canvas

The tag syntax for a Canvas is as follows:

<canvas id="canvas1" width="500" height="500">
This text is displayed if you do not have a canvas-capable browser.
</canvas>

Note how "width" and "height" are attributes just like "id". The CSS width and height are distinct and are not used for sizing the Canvas.

canvas attributes
Name/Method Description
width Default 300. Also a tag attribute, sets the width of the Canvas in pixels.
height Default 150. Also a tag attribute, sets the height of the Canvas in pixels.
toDataURL( [type, ...]) Returns a data:URL for the image in the Canvas.

The first optional argument controls the type of the image to be returned (e.g., PNG or JPEG). The default is image/png; that type is also used if the given type isn't supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.
toBlob(callback [, type, ... ]) Creates a Blob object representing a file containing the image in the Canvas and invokes a callback with a handle to that object.

The second optional argument controls the type of the image to be returned (e.g., PNG or JPEG). The default is image/png; that type is also used if the given type isn't supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.

This is an extremely new (May 2011) method for getting the contents of a Canvas. Note that it is also asynchronous.
getContext(in DOMString contextID, in any... args) Returns an object that exposes an API for drawing on the Canvas. The first argument specifies the desired API. Subsequent arguments are handled by that API.

Returns null if the given context ID is not supported or if the Canvas has already been initialized with some other (incompatible) context type (e.g. trying to get a "2d" context after getting a "webgl" context).

It is important to note that unlike many HTML Elements, width and height are attributes of the Canvas element itself and not style attributes. Setting the style width and height of the Canvas will scale the Canvas instead.

State and Transformations
Method Description
save() Pushes the current context state onto the stack.
restore() Pops the top state on the stack, restoring the context to that state.
scale(x,y) Applies a scaling transformation to the current transformation matrix
rotate(angle) Applies a rotation transformation to the current transformation matrix. The angle is in radians.
transform(m0, m1, m2, m3, m4, m5) Applies the supplied transformation matrix to the current transformation matrix.
setTransform(m0, m1, m2, m3, m4, m5) Replaces the current transformation matrix with the given transformation matrix.

The transformation matrix is an important part of drawing complex shapes on Canvas, though complete understanding of how one works is not immediately necessary. Using the rotate, scale, and translate methods will modify the matrix. It can be modified directly (but never retrieved) with transform and setTransform.

To not interfere with objects drawn after such transformations, save and restore are typically called before and after each transformed element is drawn to the Canvas.

While Canvas does not remember shapes and images drawn, it does keep track of several drawing rules that comprise its state. The methods save and restore will push or pop the state onto or off of a stack, saving and restoring not only the transformation matrix, but also the current clipping region, as well as all of the stateful attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, and textBaseline.

Composting
Property Description
globalAlpha Gets or sets the alpha value applied to all drawing operations. Default is 1.0
globalCompositeOperation Gets or sets the current composite operation. Default is "source-over".

All drawing operations are affected by the two compositing attributes. In the following images, a blue square is drawn to represent shapes already existing on a canvas, then the globalCompositeOperation is set to the specified value and a red circle is drawn.

In the following, "existing content" is defined as any pixels that were already drawn and not previously transparent.

globalCompositeOperation
Result Description
source-over

The default. New content is drawn over existing content.
source-in

New content is only drawn where existing content was non-transparent.
source-out

New content is drawn only where there was transparency.
source-atop

New content is drawn only where its overlap existing content.
destination-over

Opposite of source-over. It acts as if new content is drawn "behind" existing content.
destination-in

Opposite of source-in. Existing content is drawn only where new content is non-transparent.
destination-out

Opposite of source-out. Existing content is drawn only where new content is transparent. Acts as if existing content is drawn everywhere except the where the new content is.
destination-atop

Opposite of source-atop. New content is drawn, and then old content is drawn only where it overlaps with new content.
lighter

Where new content overlaps old content, color is determined by adding the color values.
copy

New content replaces all old content.
xor

New content is drawn where old content is transparent. Where the content of both old and new are not transparent, transparency is drawn instead.
Colors and Styles
Method/Property Description
strokeStyle Gets or sets the current style used for stroking shapes. Can be a string, CanvasGradient or CanvasPattern. The string must be parsed as a CSS color value.

Once set, changes to the CanvasGradient or CanvasPattern that was used will reflect upon newly drawn content.

Default is "#00000"
fillStyle Gets or sets the current style used for filling shapes. Follows the same rules as fillStyle. Default is "#00000".

The CanvasGradient interface defines the methods for creating linear and radial gradients. Once a gradient is created, stops are placed along it to define the color distribution. With no stops, the gradient is simply black.

Colors and Styles
Method/Property Description
addColorStop(offset, color) Adds a color stop to the gradient at the given offset. The offset goes from 0 to 1. The color is a string representation of a valid CSS color value.
context. Creates and returns a CanvasGradient object that represents a linear gradient that paints along the coordinates given. Is called on an instance of a Canvas2DContext.
CanvasPattern Methods
Method/Property Description
context.createPattern(image, repetition) Creates and returns a CanvasPattern object that uses the given image and repeats in the directions defined by the repetition argument.

The first argument must be an Image, a Canvas, or a Video element.

The allowed values for the second argument are the strings "repeat", "repeat-x", "repeat-y", and "no-repeat". The default is "repeat".

Like the gradients, this method is called on an instance of a Canvas2DContext.

Note that the CanvasGradient and CanvasPattern are distinct objects from the Canvas, but these gradients and patterns can only be created using an instance of the Canvas2DContext.Example syntax:

// creating a gradient that will display black to white along the linear path from (0,0) to (0,150)
// where context is an instance of Canvas2DContext
var gradient =  context.createLinearGradient(0,0,0,150);
gradient.addColorStop(0, '#000000');
gradient.addColorStop(1, '#FFFFFF');
ctx.fillStyle = gradient; // assignment to the context's fillStyle
Line Styles
Method/Property Description
lineWidth Gets or sets the width of lines to be drawn. Default 1.0.
lineCap Gets or sets how the end of lines are to be drawn. Valid values are "butt", "round", and "square". Default "butt".
lineJoin Gets or sets how corners are drawn when two lines meet. Valid values are "bevel", "round", and "miter". Default "miter".
miterLimit Gets or sets the current miter limit ratio. Default 10.0.

Three gray lines drawn to the thin black line. From top to bottom, the lineCap property of each is "butt", "round", and "square".

Three paths, each drawn up to the thin black line and back down. From left to right, the lineJoin property of each is "miter", "round", and "bevel".

Shadows
Method/Property Description
shadowColor Gets or sets the color of the shadow. Accepts any valid CSS color string. Default is transparent black..
shadowOffsetX Gets or sets the X offset. Pushes the shadow farther to the right. Default 0.
shadowOffsetY Gets or sets the Y offset. Default 0.
shadowBlur Gets or sets the level of blurring effect. The lower the value, the sharper the edge of the shadow. Default 0.

Shadows are "smart", emulating the drawn pixels precisely so that if text is drawn, the shadow will look just as the text does. Additionally, shadows are not affected by the transformation matrix.

A square drawn with a shadowOffsetX and shadowOffsetY of 15. The shadow is drawn evenly 15 pixels offset in both axes. To the right is the same square drawn with the same shadowOffsetX and Y, but the context was rotated about the square's center.

This means that if you were to rotate the square 180 degrees, the shadow would be in the exact same place as if the square were not rotated at all. There is an advantage to having shadows drawn unaffected by the transformation matrix. If you draw several objects, some rotated and some not, you typically want the shadows to all stay in the same direction, giving the proper illusion of a light-source. If the shadows were affected by the transformation matrix, it would look as if there is no singular light source but shadows going in every direction!

Paths
Method/Property Description
beginPath() Erases all current subpaths in preparation for drawing a new path.
closePath() Closes the subpath by drawing a straight line from the current point to the initial point.
moveTo(x, y) Creates a new subpath at the given point. Typically used to place the starting point, or to draw unconnected paths.
lineTo(x, y) Draw a line to the given point.
quadraticCurveTo(cpx, cpy, x, y) Draw a quadratic curve with the given control point (cpx, cpy) to the given point (x, y)
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) Draw a bezier curve described by the two given sets of control points and a given end point.
arcTo(x1, y1, x2, y2, radius) Draw an arc with the given control points and radius, connected to the previous point via a straight line.
arc(in double x, y, radius, startAngle, endAngle, [anticlockwise]) Draw an arc described by the circumference of the circle described by the given arguments, starting at the startAngle and ending at the endAngle , going in the given direction (defaulting to clockwise if the last argument is left blank)
rect(x, y, w, h) Add the closed subpath in the shape of a rectangle.
fill() Fills all described subpaths with the current fillStyle.
stroke() Strokes all described subpaths with the current strokeStyle.

Filling a path will fill all of the subpaths of the current path. It fills them according to the non-zero winding number rule. When a fill is called, all open subpaths get implicitly closed.

Text and Images
Method/Property Description
font Gets or sets the current font settings. Must be a string that will be parsed as a CSS font property.
textAlign Gets or sets the text alignment. Possible values are "start", "end", "left", "right", and "center". Default is "start".
textBaseline Gets or sets the baseline setting. Can be "top", "hanging", "middle", "alphabetic", "ideographic", or "bottom". Default is "alphabetic".
fillText(text, x, y, [, maxWidth]) Fills the given text at a given position using the fillStyle. Note that the position at the textBaseline.
strokeText(text, x, y, [, maxWidth]) Strokes the text at a given position using the strokeStyle.
drawImage(image, dx, dy) Draws a given image to the context at the given position. See below.
drawImage(image, dx, dy, dw, dh) Draws a given image to the context at the given position, scaling the image to the given width and height.
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) Draws a section of a given image that is described by the point and size given by (sx, sy, sw, sh), which is in turn drawn to the context at the point and size given by (dx, dy, dw, dh).

Drawing and measuring text are among some of the slowest operations on Canvas, so it is among the first places you should start fiddling around for more performance. It can often be the case that storing the result of a drawText in a PNG or a separate in-memory Canvas will improve performance.

The six different baselines, all drawn on the same Y-value, represented by the black line. "Alphabetic" shown in red is the default.

All three drawImage functions take either an image, Canvas, or video element. Even if you never think of your app asdrawing any images onto your Canvas, these methods can come in very handy. For performance reasons, you may find yourself making Canvases in memory and drawing portions of your screen to them or vice versa. If you want a miniature overlay above your complex Canvas, you can call drawImage on your
Canvas context and pass in its own Canvas to create such a mini-map.

The optional arguments to drawImage allow us to paint a portion of an image onto the canvas and force it to scale into the width and height dw and dh.

Pixel Manipulation
Method/Property Description
createImageData(sw, sh) Returns an ImageData object with the given width and height. The ImageData's pixels are filled with transparent black.
createImageData(imagedata) Returns an ImageData object with the same width and height as the given ImageData. All of the returned ImageData's pixels are transparent black.
putImageData(imagedata, dx, dy,[, dirtyX, dirtyY, dirtyWidth, dirtyHeight]) Paints a given ImageData onto the Canvas. If a "dirty" rectangle is provided, only the pixels from that rectangle are painted.

The pixels painted by putImageData are precise; globalAlpha and globalCompositeOperation are not taken into account during their painting. Because of this, you do not want to use putImageData to paint part of a Canvas to another Canvas as the transparent region will be carried over, clobbering whatever was there before.

Another reason to always consider drawImage before using putImageData is the performance difference. Working with ImageData is very slow compared to calls to drawImage, so only use it if you absolutely need to do per-pixel operations (such as making an eyedropper tool).

Also note that the optional "dirty" rectangle arguments for putImageData are not implemented on all browsers. If you use it, make sure all browsers targeted have the functionality.

ImageData Properties
Property Description
width Gets the width of the ImageData object.
height Gets the height of the ImageData object.
data Returns a one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255.

The ImageData.data property returns an array where each pixel is represented by four indices. The first pixel's R, G, B, and Alpha values are thus indicated by data[0], data[1], data[2], data[3]. The second pixel is indicated by the indices 4 to 7 and so on. The order of the pixels is from left to right, top to bottom, just like reading text in left-to-right languages.

tips for your canvas app

Web developers are no strangers to quirks, and Canvas has its own laundry list of idiosyncrasies. Below are a few things to keep in mind as you make Canvas apps.

• There are several valid ways to clear a Canvas, but some are much faster than others. Below are three common ways with their differences described:

can.width = can.width;

Setting the Canvas' width attribute equal to itself will not only clear the Canvas but also clear the entire state (see State and transformations section for what this entails). This is useful if you want a full reset, but it is typically slow.

 ctx.clearRect(0, 0, can.width, can.height);

The above merely clears the pixels on the screen; but if the transformation is not identity, it may not work as intended.

ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, can.width, can.height);
ctx.restore();

This is a good way to clear the Canvas while keeping all the state data intact. The performance difference between the use of clearRect and setting Canvas width equal to itself varies wildly between browsers. You should benchmark often on the platforms you are targeting.

• There are different ways of doing operations that have different performance effects on different browsers. For example, in the Canvas-clearing example above, it is always faster to not set Canvas width equal to itself with the lone exception of Safari 5, in which that method is two orders of magnitude faster. If you are targeting a specific browser, especially a phone or tablet, you should be sure to tailor your performance computations around it.

• In a draw loop, it is often beneficial to try and draw only the objects that have changed and (perhaps) any objects that intersect their bounds. However, depending on the application, this is not always the case. If nothing in the scene has changed, it is of course always the case that skipping out on drawing entirely is much faster.

• Use requestAnimationFrame on browsers that support it. It will ensure that animation is not occurring on non-active tabs with Canvas elements, which can save battery life on phones and tablets.

• Draw and hit test only what is on the screen.

• Hit testing only what is on the screen.

• If you are to draw the same background every time, make the background a PNG and set the Canvas' style's "background-image" attribute.

• Depending on the app, using multiple Canvases atop each other (for background, foreground, and middle ground) can increase performance.

• Keep as much out of the draw loop as possible and touch DOM objects as little as possible.

• Minimize the setting of styles. If you know that you are to draw 400,000 blue objects, set the fillStyle to blue only once at the beginning instead of before each object.

• Always draw images on integer coordinates. If you draw on non-integer coordinates the browser will have to interpolate the image (sub-pixel anti-aliasing the whole thing), which is often slower and can sometimes look quite different. A quick way to make your javascript vars into integers is to bitwise OR your vars with zero, like so:

ctx.drawImage(yourImage, x | 0, y | 0);

• Drawing images is almost always faster than drawing text or paths. If you have a repeatedly drawn string or shape that never changes and does not need to scale, consider making it into an image.

• This will "floor" any 32-bit integer quickly. Beware that when you bitwise-OR zero a number larger than a 32-bit integer, meaning 2147483648 or higher, you will get junk.

[1]. Any performance notes were based on browsers tested in the set from Firefox 3.6-7.0, Opera 11.x, IE9, Chrome 12-16 (beta versions), and Safari 5.x. Some of these varied wildly as they progressed. To get up to date performance stats I suggest creating your own tests using www.jsperf.com. Remember that simply reading the aggregate results from jsperf are not useful for cross-browser comparison unless the same hardware is used in all cases.

About The Authors

Simon Sarris is a core developer for web development at Northwoods Software. At Northwoods he is developing a fully-featured diagramming library for HTML5 Canvas. In his spare time he is an avid game programmer and hobbyist. His passion for web development is echoed in his game development projects as well as his Canvas articles and tutorials. He is among the top contributors on StackOverflow for Canvas. Recent publications are on his blog (simonsarris.com).

Recommended Book

Enterprise JavaBeans

No matter what platform or tools you use, the HTML5 revolution will soon change the way you build web applications, if it hasn't already. HTML5 is jam-packed with features, and there's a lot to learn. This book gets you started with the Canvas element, perhaps HTML5's most exciting feature. Learn how to build interactive multimedia applications using this element to draw, render text, manipulate images, and create animation.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

jQuery Selectors

By Bear Bibeault and Yehuda Katz

53,676 Downloads · Refcard 7 of 151 (see them all)

Download
FREE PDF


The Essential jQuery Selectors Cheat Sheet

jQuery Selectors are one of the most important aspects of the jQuery library, as they allow you to select and manipulate HTML elements as a group or as a single element. These selectors use familiar CSS syntax to allow page authors to quickly and easily identify any set of page elements to operate upon with the jQuery library methods. This DZone Refcard covers everything you need to know in the world of jQuery selectors, including basic CSS selectors, custom jQuery selectors, matched set methods, hot tips, and more.
HTML Preview
jQuery Selectors

jQuery Selectors

By Bear Bibeault & Yehuda Katz

What are jQuery selectors?

jQuery selectors are one of the most important aspects of the jQuery library. These selectors use familiar CSS syntax to allow page authors to quickly and easily identify any set of page elements to operate upon with the jQuery library methods. Understanding jQuery selectors is the key to using the jQuery library most effectively. This reference card puts the power of jQuery selectors at your very fingertips.

A jQuery statement typically follows the syntax pattern:

$(selector).methodName();

The selector is a string expression that identifies the set of DOM elements that will be collected into a matched set to be operated upon by the jQuery methods.

Many of the jQuery operations can also be chained:

$(selector).method1().method2().method3();

As an example, let's say that we want to hide the DOM element with the id value of goAway and to add class name incognito:

$("#goAway").hide().addClass("incognito");

Applying the methods is easy. Constructing the selector expressions is where the cleverness lies.

Hot Tip

The wrapped set created by the application of a selector can be treated as a JavaScript array for convenience. It is particularly useful to use array indexing to directly access elements within the wrapped set.

For example:

var element = $("img")[0];

will set the variable element to the first element in the matched set.

TYPES OF jQuery selectors

There are three categories of jQuery selectors: Basic CSS selectors, Positional selectors, and Custom jQuery selectors.

The Basic Selectors are known as "find selectors" as they are used to find elements within the DOM. The Positional and Custom Selectors are "filter selectors" as they filter a set of elements (which defaults to the entire set of elements in the DOM).

Basic CSS Selectors

These selectors follow standard CSS3 syntax and semantics.

Syntax Description
* Matches any element.
E Matches all elements with tag name E.
E F Matches all elements with tag name F that are descendants of E.
E>F Matches all elements with tag name F that are direct children of E.
E+F Matches all elements with tag name F that are immediately preceded by a sibling of tag name E.
E~F Matches all elements with tag name F that are preceded by any sibling of tag name E.
E:has(F) Matches all elements with tag name E that have at least one descendant with tag name F.
E.c Matches all elements E that possess a class name of c. Omitting E is identical to *.c.
E#i Matches all elements E that possess an id value of i. Omitting E is identical to *#i.
E[a] Matches all elements E that posses an attribute a of any value.
E[a=v] Matches all elements E that posses an attribute a whose value is exactly v.
E[a^=v] Matches all elements E that posses an attribute a whose value starts with v.
E[a$=v] Matches all elements E that posses an attribute a whose value ends with v.
E[a*=v] Matches all elements E that posses an attribute a whose value contains v.

Examples

  • $("div") selects all <div> elements
  • $("fieldset a") selects all <a> elements within <fieldset> elements
  • $("li>p") selects all <p> elements that are direct children of <li> elements
  • $("div~p") selects all <div> elements that are preceded by a <p> element
  • $("p:has(b)") selects all <p> elements that contain a <b> element
  • $("div.someClass") selects all <div> elements with a class name of someClass
  • $(".someClass") selects all elements with class name someClass
  • $("#testButton") selects the element with the id value of testButton
  • $("img[alt]") selects all <img> elements that possess an alt attribute
  • $("a[href$=.pdf]") selects all <a> elements that possess an href attribute that ends in .pdf
  • $("button[id*=test]") selects all buttons whose id attributes contain test

Hot Tip

You can create the union of multiple disparate selectors by listing them, separated by commas, in a single call to $(). For example, the following matches all <div> and <p> elements:

$("div,p")

While the following, matches all <div> elements with a title attribute, and all <img> elements with alt attributes:

$("div[title],img[alt]")

Positional Selectors

These selectors match based upon positional relationships between elements. These selectors can be appended to any base selector (which we"ll denote by B) to filter the matches based upon position. If B is omitted, it is assumed to be * (the pool of all elements).

Syntax Description
B:first Selects the first element on the page matching the base selector B.
B:last Selects the last element on the page matching the base selector B.
B:first-child Selects all elements from B that are first children.
B:last-child Selects all elements from B that are last children.
B:only-child Selects all elements from B that are only children.
B:nth-child(n) Selects all elements from B that are n-th ordinal children. Starts at 1.
B:nth-child(odd|even) Selects all elements from B that are even or odd ordinal children. The first child is considered odd (ordinal 1).
B:nth-child(Xn+Y) Selects all elements from B that match the formula. X denotes an ordinal multiplier, while Y denotes an offset. Y may be omitted if 0. See the following examples.
B:even Selects the even elements within the set of elements defined by B.
B:odd Selects the odd elements within the set of elements defined by B.
B:eq(n) Selects the n-th element within the set of elements defined by B. Starts at 0.
B:gt(n) Selects elements within the set of elements defined by B that follow the n-th element (exclusive). Starts at 0.
B:lt(n) Selects elements within the set of elements defined by B that precede the n-th element (exclusive). Starts at 0.

Examples

  • $("p:first") selects the first

    element on the page

  • $("img[src$=.png]:first") selects the first <img> element on the page that has a src attribute ending in .png
  • $("button.small:last") selects the last <button> element on the page that has a class name of small
  • $("li:first-child") selects all <li> elements that are first children within their lists
  • $("a:only-child") selects all <a> elements that are the only element within their parent
  • $("li:nth-child(2)") selects all <li> elements that are the second item within their lists
  • $("tr:nth-child(odd)") selects all odd <tr> elements within a table
  • $("div:nth-child(5n)") selects every 5th <div> element
  • $("div:nth-child(5n+1)") selects the element after every 5th <div> element
  • $(".someClass:eq(1)") selects the second element with a class name of someClass
  • $(".someClass:gt(1)") selects all but the first two elements with a class name of someClass
  • $(".someClass:lt(4)") selects the first four elements with a class name of someClass

Hot Tip

Note that the :nth-child selectors begin counting at 1, while the :eq, :gt and :lt selectors begin with 0.

jQuery Custom Selectors

These selectors are provided by jQuery to allow for commonly used, or just plain handy, selections that were not anticipated by the CSS Specification. Like the Positional Selectors, these selectors filter a base matching set (which we denote with B). Omitting B is interpreted as the set of all elements. These selectors may be combined; see the examples for some powerful selector combinations.

Syntax Description
B:animated Selects elements from the base set B that are currently under animated control via one of the jQuery animation methods.
B:button Selects elements of B that are of any button type; that is: button, input[type=submit], input[type=reset] or input[type=button].
B:checkbox Selects elements of B that are of type input[type=checkbox].
B:enabled Selects form elements from B that are in enabled state.
B:file Selects elements of B that are of type input[type=file].
B:header Selects elements from B that are of the header types: that is <h1> through <h6>.
B:hidden Selects elements of B that are hidden.
B:image Selects elements of B that are of type input[type=image].
B:input Selects form input elements from B; that is, <input>, <select>, <textarea> and <button> elements.
B:not(f) Selects elements of B that do not match the filter selector specified by f. A filter selector is any selector beginning with : (colon), A base set B cannot be specified as part of f.
B:parent Selects elements of B that are parents of non-empty element children.
B:password Selects elements of B that are of type input[type=password].
B:radio Selects elements of B that are of type input[type=radio].
B:reset Selects elements of B that are of type input[type=reset] or button[type=reset].
B:selected Selects elements of B that are in selected state. Only <option> elements posses this state.
B:submit Selects elements of B that are of type input[type=submit] or button[type=submit].
B:text Selects elements of B that are of type input[type=text].
B:visible Selects form elements from B that are not hidden.

Examples

  • $("img:animated") selects all <img> elements that are undergoing animation
  • $(":button:hidden") selects all button type elements that are hidden
  • $("input[name=myRadioGroup]:radio:checked") selects all radio elements with the name attribute value of myRadioGroup that are checked
  • $(":text:disabled") selects all text fields that are disabled
  • $("#xyz p :header") selects all header type elements within <p> elements that are within an element with an id value of xyz. Note the space before :header that prevents it from binding directly to the p.
  • $("option:not(:selected)") selects all unselected <option> elements
  • $("#myForm button:not(.someClass)") selects all buttons from the <form> with the id of myForm that do not possess the class name someClass.
  • $("select[name=choices] :selected") selects the selected <option> elements within the <select> element named choices.
  • $("p:contains(coffee)") selects all <p> elements that contain the text coffee

Used either separately, or in combination, the jQuery selectors give you a great deal of power to easily create a set of elements that you wish to operate upon with the jQuery methods.

MATCHED SET METHODS

While the jQuery selectors give us great flexibility in identifying which DOM elements are to be added to a matched set, sometimes there are match criteria that cannot be expressed by selectors alone. Also, given the power of jQuery method chaining, we may wish to adjust the contents of the matched set between method invocations.

For these situations, jQuery provides methods that operate not upon the elements within the matched set, but on the matched set itself. This section will summarize those methods.

Adding New Elements

For adding new elements to a matched set, the add() method is provided:

add(expression)
expression (String) A selector expression that specifies the DOM elements to be added to the matched set, or an HTML string of new elements to create and add to the set.
(Element) A reference to an existing element to add.
(Array) Array of references to elements to add.

The add() method returns a new matched set that is the union of elements in the original wrapped set and any elements either passed directly as the expression argument, or matched by the selector of the expression argument.

Consider:

$("div").add("p").css("color","red");

This statement creates a matched set of all <div> elements, then creates a new matched set of the already matched <div> elements and all <p> elements. The second matched set"s elements (all <div> and all <p> elements) are then given the CSS color property of "red".

You may think this is not all that useful because the same could have been achieved with:

$("div,p").css("color","red");

But now consider:

$("div").css("font-weight","bold").add("p"). css("color","red");

Here the first created matched set of <div> elements is assigned a bold rendition, and then the second matched set, with <p> elements added, is colored red.

jQuery chaining (in which the css() method returns the matched set) allows us to create efficient statements such as this one that can accomplish a great deal with little in the way of script.

More Examples

$("div").add(someElement).css("border","3px solid pink");
$("div")
.add([element1,element2])
.css("border","3px solid pink");

Removing Matched Elements

What if we want to remove elements from the matched set? That"s the job of the not() method:

not(expression)
expression (String) A selector expression that specifies the DOM elements to be removed from the matched set.
(Element) A reference to an existing element to remove.
(Array) Array of references to elements to remove.

Like add(), this method creates and returns a new matched set, except with the elements specified by the expression argument removed. The argument can be a jQuery selector, or references to elements to remove.

Examples

$("body *").css("font-weight","bold")
.not("p").css("color","red");

Makes all body elements bold, then makes all but

elements red.

$("body *").css("font-weight","bold")
.not(anElement).css("color","red");

Similar to the previous except the element referenced by variable anElement is not included in the second set (and therefore not colored red).

Hot Tip

Avoid a typical beginner"s mistake and never confuse the not() method, which will remove elements from the matched set, with the remove() method, which will remove the elements in the matched set from the HTML DOM!

Finding Descendants

Sometimes it"s useful to limit the search for elements to descendants of already identified elements. The find() method does just that:

find(expression)
expression (String) A selector expression that specifies which descendant elements are to be matched.

Unlike the previously examined methods, find() only accepts a selector expression as its argument. The elements within the existing matched set will be searched for descendants that match the expression. Any elements in the original matched set that match the selector are not included in the new set.

Example

$("div").css("background-color","blue")
.find("img").css("border","1px solid aqua");;

Selects all <div> elements, makes their background blue, selects all <img> elements that are descendants of those <div> elements (but not <img> elements that are not descendants) and gives them an aqua border.

Filtering Matched Sets

When really fine-grained control is required for filtering the elements of a matched set, the filter() method comes in handy:

filter(expression)
expression

(String) A selector expression that specifies which elements are to be retained.

(Function) A function used to determine if an element should be included in the new set or not. This function is passed the zero-based ordinal of the element within the original set, and the function context (this) is set to the current element. Returning false as the function result causes the element to not be included in the new set.

The filter() method can be passed either a selector expression (comma-separated if more than one is desired) or a function. When passed a selector, it acts like the inverse of not(), retaining elements that match the selector (as opposed to excluding them). When passed a function, the function is invoked for each element and decisions that cannot be expressed by selectors can be made regarding the exclusion or inclusion of each element.

Examples

$(".bashful").show()
.filter("img[src$=.gif]").attr("title","Hi there!");

Selects all elements with class name bashful, makes sure that they are visible, filters the set down to just GIF images, and assigns a title attribute to them.

$("img[src^=images/]").filter(function(){
return $(this).attr("title").match(/.+@.+\.com/)!= null;
})
.hide();

Selects images from a specific folder, filters them to only those whose title attribute matches a rudimentary .com email address, and hides those elements.

Slicing and Dicing Matched Sets

Rather than matching elements by selector, we may sometimes wish to slice up a matched set based upon the position of the elements within the set. This section introduces two methods that do that for us.

Both of these methods assume zero-based indexing.

slice(being,end)
begin

(Number) The beginning position of the first element to be included in the new set.

end (Number) The end position of the first element to not be included in the new set. If omitted, all elements from begin to the end of the set are included.

Examples

$("body *").slice(2).hide();

Selects all body elements, then creates a new set containing all but the first two elements, and hides them.

$("body *").slice(2,3).hide();

Selects all body elements, then creates a new set containing the third element in the set and hides it. Note that the new set contains just one element: that at position 2. The element at position 3 is not included.

eq(position)
position

(Number) The position of a single element to be included in the new set.

The eq(n) method can be considered shorthand for slice(n,n+1).

Matching by Relationship

Frequently we may want to create new matched sets based upon relationships between elements. These methods are similar enough that we"ll present them en masse in the following table:

Method Description
children(expression) Creates a new matched set containing all unique children of the elements in the original matched set that match the optional expression.
next(expression) Creates a new matched set containing unique following (next) siblings of the elements in the original matched set that match the optional expression. Only immediately following siblings are returned.
nextAll(expression) Creates a new matched set containing unique following (next) siblings of the elements in the original matched set that match the optional expression. All following siblings are returned.
parent(expression) Creates a new matched set containing unique immediate parents of the elements in the original matched set that match the optional expression.
parents(expression) Creates a new matched set containing all ancestors of the elements in the original matched set that match the optional expression.
prev(expression) Creates a new matched set containing unique preceding siblings of the elements in the original matched set that match the optional expression. Only immediately preceding siblings are returned.
prevAll(expression) Creates a new matched set containing unique preceding siblings of the elements in the original matched set that match the optional expression. All preceding siblings are returned.
siblings(expression) Creates a new matched set containing unique siblings of the elements in the original matched set that match the optional expression.
contents() Creates a new matched set containing all unique children of the elements in the original matched set including text nodes. When used on an <iframe>, matches the content document.

For all methods that accept a filtering expression, the expression may be omitted in which case no filtering occurs.

Translating Elements

There may be times that you want to translate the elements within a matched set to other values. jQuery provides the map() method for this purpose.

map(callback)
callback (Function) A callback function called for each element in the matched set. The return values of the invocations are collected into an array that is returned as the result of the map() method. The current element is set as the function context (this) for each invocation.

For example, let"s say that you wanted to collect the values of all form elements within a form named myForm:

var values = $("#myForm :input").map(function(){
return $(this).val();
});

Hot Tip

The map() function returns a jQuery object instance. To convert this to a normal JavaScript array, you can use the get() method without parameters:

var values = $("#myForm :input").map(function(){
return $(this).val();
}).get();

In this case, values references a JavaScript array rather than a jQuery wrapped object.

Controlling Chaining

All of the methods examined create new matched sets whose contents are determined in the manner explained for each method. But what happens to the original? Is it dismissed? It is not. When a new wrapped set is created it is placed on the top of a stack of sets, with the top-most set being the one to which any methods will be applied (as we have seen in the examples). But jQuery allows you to "pop" the top-most set off that stack so that you can apply methods to the original set. It does this with the end() method:

end()
(no arguments)  

Consider a previous example:

$("div").add("p").css("color","red");

As we recall, this creates a matched set of <div> elements, then creates a new set that also contains the <p> elements. Since this latter set is at the top of the stack when the css() method is called, it is the second set that is affected. Now consider:

$("div").add("p").css("color","red").end().hide();

After the css() method is called, the end() method pops the second set off the stack "exposing" the original set of just <div> elements, which are then hidden.

Another useful method to affect how chaining the sets operates is the andSelf() method:

andSelf()
(no arguments)  

Calling andSelf() creates yet another new matched set that is the union of the top two matched sets on the stack. This can be useful for performing an action on a set, creating a new distinct set, and then applying a method (or methods) to them all. Consider:

$("div").css("background-color","yellow")
.children("img").css("border","4px ridge maroon")
.andSelf().css("margin","4em");

All <div> elements are selected and their background set to yellow. Then, the <img> children of those <div> elements are selected and have a border applied. Finally, the two sets are merged, and a wide margin is applied to all <div> elements and their <img> children.

Between jQuery selectors and the jQuery methods that allow us to manipulate the matched sets, we can see that jQuery gives us some powerful tools to select the DOM elements that we can then operate upon with the many jQuery methods (as well as the dozens and dozens of jQuery plugins) that are available to us.

About The Authors

Photo of author Bear Bibeault

Bear Bibeault

Bear Bibeault has been writing software for over three decades, starting with a Tic-Tac-Toe program written on a Control Data Cyber supercomputer via a 100-baud teletype. He is a Software Architect and Technical Manager for a company that builds and maintains a large financial web application used by the accountants that many of the Fortune 500 companies keep in their dungeons. He also serves as a "sheriff" at the popular JavaRanch.com.

Publications
Notable Projects:

Photo of author Yehuda Katz

Yehuda Katz

Yehuda Katz has been involved in a number of open-source projects over the past several years. In addition to being a core team member of the jQuery project, he is also a core member of Merb, an alternative to Ruby on Rails (also written in Ruby). He speaks about jQuery and Ruby at a number of regional conferences, and is the JavaScript expert on the Merb team. He recently joined EngineYard working on the Merb project full-time.

Publications
Notable Projects:
Web site:

Recommended Book

Book cover of jQuery in Action

jQuery in Action is a fast-paced introduction and guide to the jQuery library. It shows you how to traverse HTML documents, handle events, perform animations, and add Ajax to your web pages using jQuery. You learn how jQuery interacts with other tools and how to build jQuery plugins.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose: Java 7 Webcast to Unveil Latest Innovations

Tomorrow at 9:00 am PT, Oracle will be hosting multi-city events and live webcasts for the Java community  detailing the newest innovations for Java 7. The event will highlight the RC release of Java with sessions discussing:

0 replies - 13525 views - 07/06/11 by Ross Jernigan in Daily Dose

Daily Dose: jQuery Mobile Beta 1 Released

This week has started off with a lot of great releases! First of all, the first beta version of jQuery Mobile, the HTML5 library for building mobile web sites and apps, was released. The new version adds support for Opera Mini and BlackBerry 5 devices, in...

0 replies - 11696 views - 06/21/11 by Ross Jernigan in Daily Dose

Daily Dose: U.S. IT Employment Back to Pre-Recession Levels

Good news for IT folks from the U.S. Bureau of Labor Statistics, IT employment has finally regained what it lost in the recession. During the recession, nearly 200,000 IT jobs were lost to layoffs by technology companies. This month, statistics show that...

0 replies - 18784 views - 05/23/11 by Ross Jernigan in Daily Dose

Daily Dose - Will NetBeans Have to Remove JUnit?

NetBeans Platform Architect Jaroslav Tulach recently posted some surprising news on the JUnit Yahoo Group.  "We have new lawyers," he said, and they're concerned about the JUnit license—the Common Public License, which is a bit dated in Tulach's...

0 replies - 14539 views - 01/18/11 by Mitchell Pronsc... in Daily Dose

Daily Dose - Mozilla Jetpack Becomes 'Add-On SDK' - Reaches 1.0 Beta

The Mozilla Jetpack project, which is now changing its name, has reached version 1.0 Beta 1.  Its current APIs are quite stable and more will be implemented in the coming months.  Mozilla engineer Daniel Buchner has created a chart comparing Firefox,...

1 replies - 18089 views - 12/13/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - U.S. Dept. of Justice Receives Complaint About Oracle Tactics

"Oracle’s position appears to be the most onerous and draconian of any major hardware manufacturer," claims Claudia Betzner, the executive director of the US Service Industry Association (SIA).   That was a quote from the SIA's recent letter to...

0 replies - 24214 views - 11/19/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Translating the PR-Speak in Oracle's Reply to the ASF

Over the last two days the back-and-forth over TCKs continued between Apache and Oracle.  Stephen Colebourne, a certified Java Champion, knows this issue very well and was "amused" that Oracle would describe their TCK distribution terms as...

0 replies - 20171 views - 11/17/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Google Fires Back: 'Oracle Doctored the Code in Question'

Google presented a new document to the court in the Oracle-Android case.  In the document, Google says that they did not copy Oracle's Java APIs and that Oracle had revised or deleted essential passages in the evidence that attempts to prove Google's...

0 replies - 22720 views - 11/13/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - First Release of OpenStack is Out

The OpenStack project for open source, interoperable cloud computing and storage controllers has just released its first public version, codenamed "Austin."  Developers were surprised by the amount of active participation that has moved the project...

1 replies - 13296 views - 10/22/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - SproutCore 1.4 Grows Touch Support

A new release arrived for the SproutCore framework that builds nativeized web apps.  The new release, 1.4, has more touch events for mobile devices and better animation support.  The build tools such as Abbot have gotten a speed boost in this release. ...

0 replies - 15493 views - 09/21/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - PostgreSQL 9 Released Ahead of Announcement

Before the official announcement went out, the final version of PostgreSQL was released this weekend.  If you browsed the PostgreSQL FTP server you could find the final packages for this major update.  MySQL and Oracle better watch their back because...

0 replies - 17412 views - 09/20/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Gemini Web M4 Upgrades Tomcat 6.0.29

The fourth milestone of Gemini Web (formerly Spring Dynamic Modules) was released today with various test and build improvements.  The project has also brought upgrades to Tomcat 6.0.29 that close security holes.  The changes also make embedded Tomcat work...

0 replies - 15957 views - 09/09/10 by Mitchell Pronsc... in Daily Dose