Version 1.1 by Jon Ippolito

Background Sample scripts How JavaScript works Sample Exercise Resources

Background

Why JavaScript?

Cross Platform LanguagesJavaScript is an increasingly ubiquitous language. It can be used to program everything from AJAX-driven Web sites to iPhone applications, from Photoshop actions to bookmarklets. Its dialects can be used to script environments like Flash, AIR, Firefox, PDF, and Max/MSP.

Compared to other languages, JavaScript has an easy learning curve (especially when combined with HTML5) and broad platform support. For more information, see this chart comparing cross-platform languages.

This page gives an example of a simple JavaScript that can be run, with small modifications, in environments ranging from a Web page to a desktop application to an image editor.

Prerequisites

To experiment with this script, you'll need a basic familiarity with Photoshop (such as how to create layers and place images on them) or HTML (such as where to put styles and scripts and how to launch a script when the page loads or when a user clicks on a link).

You'll find more references on using JavaScript on various platforms at the bottom of this page.

Sample scripts

The following downloadable demos illustrate the same JavaScript applied to three different platforms. Inspired by a Photoshop script by Amy Pierce, each copies a single layer with a small image on it (a "bokeh," in the parlance of photographers) repeatedly to fill the screen. Click on any link to download a zipped directory with all the files necessary to run the JavaScript. (In the case of Web and Widget demos, the script is embedded in an HTML file for simplicity).

JavaScript Web DemoJavaScript Widget DemoJavaScript Photoshop Demo

What they do

The process executed by the JavaScript is roughly as follows:

  1. Identify the page's dimensions and the "bokeh" layer and its dimensions.
  2. Clone the bokeh layer.
  3. Move it to a random position.
  4. Give it a random opacity.
  5. Give it a random size.
  6. Loop to repeat steps 2-5 for a given number of times.

Depending on the "seed" bokeh and background used, each script can generate an image such as the following when completed.

Javascript Demo Cat Result B
Javascript Demo Disk Result C
Lotsa Salmon Vga

You can see the Web version of the script in action in your browser by visiting this online demo. Amy Pierce describes her version of the script, which she used to create artificial lens effects, in this screencast.

Each script contains detailed comments explaining how it works. Read on to learn how to run and customize these scripts.

How JavaScript works

The core of JavaScript is a standards-defined language (ECMAScript) that never changes. However, JavaScript is rarely run in isolation, but is usually inflected with properties and methods that help it communicate with its environment. The following sections give examples of syntax that works across platforms, varies with platform, or is unique to a specific platform.

Cross-platform syntax

Regardless of where it runs, most of JavaScript's syntax remains the same, as in the following examples.

Comments and alerts

	// Single line comment.
/* Multiple- line comment */

alert("This will pop up a message with this text as the content")

Variables

Local

var myCatAge = 9 defines a variable that can only be accessed in its original context.

Global

myCatAge = 9 defines a variable that can be accessed anywhere.

Types

Strings look like "Morris", integers like 13

Objects

Separate objects from properties or methods with a dot: window.innerWidth or window.close()

Math

Math.random() creates a random number between 0 and 1 (such as 0.273465)

0.273465 * 10 means multiply by ten.

parseInt( 2.73465 ) extracts the integer part (2). Math.floor() or Math.round() are similar.

Loops

	for (var catCounter = 0 ; catCounter < 30 ; catCounter++ ) {
		cloneCat() ;
	} ;	

Platform dialects

JavaScript is most often used to manipulate elements of the environment itself, such as Art layers in Photoshop or <div> layers in HTML. So it would make sense that each of these would vary slightly by platform.

Item Web Widget Adobe
JavaScript location Embedded or linked as cats.js Embedded or linked as cats.js On harddrive as cats.jsx
Run JavaScript Trigger onload or onclick Trigger onload or onclick File > Scripts > Browse...
Environment window window app
Current document window.document window.document app.activeDocument
Document dimensions window.innerWidth, .innerHeight (as integers) Set in Info.plist via <key>Width</key> (as integers) app.activeDocument.width.value, .height.value (as integers)
Layer <div id="cat"> tag <div id="cat"> tag cat layer
Identify a layer document.getElementById( cat ) document.getElementById( cat ) app.activeDocument.layers.getByName( cat )
Duplicate a layer var newCat = oldCat.cloneNode( true ) ; document.body.appendChild( newCat ) var newCat = oldCat.cloneNode( true ) ; document.body.appendChild( newCat ) var newCat = oldCat.duplicate()
Get a layer's position newCat.style.left (as pixels)
newCat.style.top (as pixels)
newCat.style.left (as pixels)
newCat.style.top (as pixels)
newCat.bounds[ 0 ] ) (left as pixels)
newCat.bounds[ 1 ] ) (top as pixels)
Reposition a layer newCat.style.left = "200px" newCat.style.left = "200px" newCat.translate( "20px" , "10px" ) (as left, top shifts from present position)
Resize a layer newCat.style.width = "100px" newCat.style.width = "100px" newCat.resize( 50 , 50 ) (as percents)
Make a layer transparent newCat.style.opacity = .5 newCat.style.opacity = .5 newCat.fillOpacity = 50 (as percent)

Platform-unique syntax

Some JavaScript syntax is specific to a given environment and doesn't have an exact parallel in other environments.

Web pages and Widgets

Both Web pages and Widgets are based on HTML for structure such as text and images, and Cascading Stylesheets (CSS) for design such as colors and fonts.

Styles

Choices about position, opacity, and so forth that don't change can be set inside <style> tags or in a linked stylesheet like cats.css.

Positioning

Adding position: absolute to the style means all positions will be measured from upper left.

Waiting for load

Some variables or actions depend on elements in the rest of the HTML, so you can't refer to them except by waiting until the entire page loads. This is accomplished by wrapping the code in a function and then calling that function via an onload attribute in the body tag:

		<script>
			function prepareCats( ) {
				do something with HTML here...
			} ;
		</script>
		<body onload="prepareCats( )">
		...		

Widgets

Dashboard Widgets, Yahoo Widgets, and the like are mini-applications that run on a computer desktop. Unlike full-scale applications, they tend to be devoted to a single task, such as a timer, a news reader, or a weather report.

In OS X, you create a Widget by adding the appropriate files to a folder and then renaming it with a .wdgt extension, at which point it becomes a "package" (like an application icon) that can be double-clicked to activate.

Folder contents

Background images

Default.png

Icon.png

Info.plist

Put in your widget's name under CFBundleName (myWidget), MainHTML (myWidget.html), and in CFBundleIdentifier (com.apple.widget.myWidget).

Put your widget's Height and Width as integers.

HTML file

This is where your HTML, styles, and JavaScript can go. Alternatively, you can link them to this file just as you would a Web page.

Activate your widget

Save a copy of the folder, and rename the original with a .wdgt extension. Then double-click on this and follow the instructions. It will end up in your home Library > Widgets folder.

(You should make a copy because if you delete your widget from Dashboard you'll delete it from your system.)

Look inside a widget

Right- or Control-click on a widget and choose View package contents, or remove the .wdgt extension to turn it back into a folder.

Adobe applications

Adobe applications such as Photoshop and Illustrator can be scripted to automate repetitive tasks or introduce random or algorithmic elements to a composition. Adobe Flash uses scripting more intensively--specifically a version of JavaScript called ActionScript (not discussed here).

If you get tired of running JavaScripts via Adobe's pull-down menu, you can record the process of selecting it and save the resulting action to a button in the Actions panel.

Set preferences

app.preferences.rulerUnits = Units.PIXELS

app.displayDialogs = DialogModes.NO

Flatten layers

app.activeDocument.flatten()

Sample Exercise

Part 1

Choose one of the environments listed in this handout, run the script inside a file you have made yourself, and post the results to the folder indicated by your instructor:

Part 2

Experiment with changing the script's parameters such as the number of copies, the size and position on the page, or other aspects. Save each version (myScript_v01.0.js, myScript_v01.1.js, etc.) as you add incremental modifications.

Keep making small changes until the script no longer works as intended (eg, you get an error). Then post the last working version and the first version that stopped working to the folder indicated by your instructor. (If you ran a Photoshop script, also post the resulting JPEG image.)

Resources

Web pages

W3Schools

Google javascript blah (there are thousands of free resources online).

OS X Widgets

Andrew Hedges' "Developing Dashboard Widgets"

Apple's list of Dashboard Programming Topics

O'Reilly tutorials, "Build a Dashboard Widget"

Adobe JavaScript

Adobe Photoshop Developer Center (Adobe.com)

Adobe Photoshop Scripting Forum (Adobe.com)

Adobe Studio Exchange – Photoshop Scripts (Adobe.com)

Working With Photoshop Scripts (PhotoshopSupport.com)

Photoshop Scripting using JavaScript (Tranberry.com)

Free Scripts for Photoshop (Morris-Photographics.com)

Photoshop Scripting Community Forum (PS-Scripts)