February 13, 2012

CSS Regions: What’s Possible Now, and What’s Coming


I just made a quick screencast to show the current state of CSS Regions, and to demonstrate some new capabilities that will be here soon. In general, there are two aspects to CSS Regions:

  1. The ability to have text automatically flow between regions.
  2. The ability to hook into that flow using JavaScript in order to create more dynamic layouts.

If you use Chrome (Adobe’s work on CSS Regions is in WebKit which Chrome uses), you can go ahead and see text flow already working (including Chrome for Android). Other browsers have already committed to supporting CSS Regions, and we should know more about when their implementations will land soon. Let me know below if you have any comments or questions.

10:01 PM Comments (7) Permalink
February 9, 2012

CSS Regions Support in Google Chrome for Android

I’ve been working on some CSS Regions prototypes recently (if you’re new to CSS Regions, check out this post), so when the Chrome for Android beta came out the other day, I decided to see how some of my samples looked on mobile. It turns out, they work perfectly:

The CSS Regions capabilities currently in Chrome are pretty rudimentary, but I’m also working with some nightly WebKit builds which definitely take the feature to the next level (they include CSS Object Model support which enables the scripting of CSS Regions — that’s when they get really interesting). I’ll have plenty more samples and prototypes in the near future.

7:04 PM Comments (0) Permalink
February 3, 2012

Setting Text Selection Colors in JavaScript

If you’re building any kind of a text editor in JavaScript, you might want to be able to dynamically set or change the text selection color. I discovered it wasn’t as easy to do as I expected it to be, so I thought I’d share the code. I created this extreme (and admittedly, somewhat obnoxious) example showing the selection color changing as the mouse moves, but the core of the code is something like this:

var ss = document.styleSheets[0];
ss.insertRule('#content::selection {color: #'+
              newForegroundColor+'; background: #'+
              newBackgroundColor+';}', 0);

Note that I only tested this code in Chrome and Safari (I’m only targeting WebKit browsers for now), however it can work with Firefox with the correct "moz" prefixed style name. I haven’t yet tested or investigated IE.

If you know another way of changing text selection properties in JavaScript, let me know.

4:18 PM Comments (2) Permalink
January 31, 2012

How to Create a Custom File Input (For Use With the HTML5 File APIs)

I’m working on an HTML/JS application that lets users work with local files directly in the browser, and I’m using some new HTML5 APIs to access local files. It works great (in Chrome and Firefox, anyway — see note below), however my UI calls for a custom file input rather than the default (and usually pretty ugly) button-and-path input. Fortunately, customization is easy in this case. The trick is to create your own UI treatment (in my case, just a link), then use the click() function on a hidden file input to bring up the file dialog.

In Firefox, you can use the display:none style as noted in this Mozilla Developer Network documentation, however this won’t work in Chrome or Safari (although FileReader is currently not supported in Safari, you might as well think ahead for when it is). A better way of doing it, therefore, is to use visibility:hidden.

The only problem is that when something is hidden using its visibility property, it’s still actually in the DOM, and space is therefore allocated for it even though you can’t see it. If you want to get your file input completely out of the way, therefore, you can use something like this:

<input type="file" id="fileInput" onchange="handleFiles(this.files)" style="visibility:hidden;position:absolute;top:-50;left:-50"/>

Your file input will still be in the DOM (even though it’s hidden and off-screen), however it won’t take up any visual space.

Here’s the full HTML code:

<a href="javascript:onLoad();">Load a File!</a>
<input type="file" id="fileInput" onchange="handleFiles(this.files)" style="visibility:hidden;position:absolute;top:-50;left:-50"/>

And here’s the JavaScript code:

function onLoad() {
    id('fileInput').click();
}

function handleFiles(files) {
    var file = files[0];
    var reader = new FileReader();
    reader.onload = onFileReadComplete;
    reader.readAsText(file);
}

function onFileReadComplete(event) {
  // Do something fun with your file contents.
}

Note that this code is only going to work in current versions of Chrome and Firefox, but is expected to work in future versions of IE (10) and Safari (6).

7:42 PM Comments (1) Permalink
January 27, 2012

How to Download Data as a File From JavaScript

I’m currently working on an HTML/JavaScript application that allows you to author content entirely on the client. I want to let users download that content and save it locally, but without bouncing it off a server. After some trial and error, I have it working fairly well using a data URI. Rather than explain it, it’s probably easiest just to show the code:

HTML:

<a href="javascript:onDownload();">Download</a>

JavaScript code:

function onDownload() {
    document.location = 'data:Application/octet-stream,' +
                         encodeURIComponent(dataToDownload);
}

The only limitation is that I can’t figure out a way to give the downloaded file a name (and have concluded that it’s not currently possible, though I’m happy to be proven wrong). I’ve only tested the code in Safari and Chrome, and in both cases, the file name defaults to "download" (with no extension). All the data is in the file, but it’s not a very intuitive experience for the end user.

I’ll be releasing the application shortly which should demonstrate why downloading data directly from the client can be useful. In the meantime, I’m curious if this is something any of you might use, and if so, if you think the file name issue should be fixed.

Let me know in the comments.

5:36 PM Comments (9) Permalink
January 17, 2012

A Summary of the WebKit Developer Tools

I use the WebKit developer tools extensively in both Chrome and Safari, but it occurred to me the other day that I was probably only using a fraction of their capabilities. After researching them more fully, I was pleasantly surprised by how comprehensive they are, so I decided to make a quick list of all the major developer-oriented features of WebKit that I know of. Even if you use the Chrome/WebKit dev tools regularly, there’s a good chance you’ll find one or two things below you haven’t been leveraging.

Continue reading…

8:00 PM Comments (1) Permalink
December 14, 2011

Creating a Loading Spinner Animation in CSS and JavaScript

Update (12/20/2011): Now works in Firefox as well as Chrome and Safari.

Since I’m not a very good designer, I usually try to do as much styling, design, and graphics in code as I can. For instance, when I wrote this mobile compass application in HTML, I did all the graphics programmatically using Canvas and CSS.

I’m now working on a project that requires one of those loading spinner animations that Apple seems to have made famous, so naturally, I started looking into ways to create one purely in code and/or CSS (no external assets). Fortunately, I found a great post on the Signal vs. Noise blog demonstrating exactly what I wanted to do. However, I decided to take it one step further, and write some JavaScript to generate both the required CSS and the HTML. The advantage of generating everything dynamically is that you can configure things like the size, color, and the number of bars in the animation at runtime.

Here’s an example of some randomly generated loading spinner animations which are 100% CSS and HTML generated by JavaScript (Chrome and Safari only for now). If you’re interested in the code, here’s the original CSS from Signal vs. Noise, and below is my port to JavaScript (view the source of the demo to see how to use it). It only works in WebKit-based browsers for the time being, but I’ll update it as browser capabilities get better. It works in WebKit-based browser, and in Firefox.

Check out the example.

var Spinner = {
  SPINNER_ID: '_spinner',
  prefix: (navigator.userAgent.indexOf('WebKit') != -1) ? 'webkit' : 'moz',
  getSpinner: function(size, numberOfBars, color) {
    if (document.getElementById(this.SPINNER_ID) == null) {
      var style = document.createElement('style');
      style.setAttribute('id', this.SPINNER_ID);
      style.innerHTML = '@-'+this.prefix+'-keyframes fade {from {opacity: 1;} to {opacity: 0.25;}}';
      document.getElementsByTagName('head')[0].appendChild(style);
    }
    var spinner = document.createElement('div');
    spinner.style.width = size;
    spinner.style.height = size;
    spinner.style.position = 'relative';
    var rotation = 0;
    var rotateBy = 360 / numberOfBars;
    var animationDelay = 0;
    var frameRate = 1 / numberOfBars;
    for (var i = 0; i < numberOfBars; ++i) {
      var bar = document.createElement('div');
      spinner.appendChild(bar);
      bar.style.width = '12%';
      bar.style.height = '26%';
      bar.style.background = color;
      bar.style.position = 'absolute';
      bar.style.left = '44.5%';
      bar.style.top = '37%';
      bar.style.opacity = '1';
      bar.style.setProperty('-'+this.prefix+'-border-radius', '50px', null);
      bar.style.setProperty('-'+this.prefix+'-box-shadow', '0 0 3px rgba(0,0,0,0.2)', null);
      bar.style.setProperty('-'+this.prefix+'-animation', 'fade 1s linear infinite', null);
      bar.style.setProperty('-'+this.prefix+'-transform', 'rotate('+rotation+'deg) translate(0, -142%)', null);
      bar.style.setProperty('-'+this.prefix+'-animation-delay', animationDelay + 's', null);
      rotation += rotateBy;
      animationDelay -= frameRate;
    }
    return spinner;
  }
}

9:48 PM Comments (6) Permalink
December 7, 2011

Loading Data Across Domains with JavaScript

I’m working on a project now that makes heavy use of XHR (XMLHttpRequest) to load data from a server. I’m writing the HTML/JS portion of the application on my local machine, but my server development environment is on a remote server under a different domain. Typically cross-domain XHR request aren’t allowed due to browser security restrictions, however there are two easy work-arounds:

  1. JSONP
  2. Cross-Origin Resource Sharing

JSONP

JSONP gets around the same origin policy by loading JavaScript from another domain into a dynamically generated <script> tag (script tags are not subject to the same origin policy which is what enables things like ads to be served from different domains). In your request (formed as the src attribute of the script tag), you typically specify a callback function that you have already defined in your application. The JavaScript that gets loaded into the dynamically generated script tag will call the specified function, passing in the requested JSON data.

(Note that JSONP requests are probably best handled by robust frameworks like the jQuery.getJSON() function.)

I’ve used JSONP in the past for things like this prototype client-side news reader, but the project I’m working on now uses XML as well as JSON, so I decided to use a different approach.

Cross-Origin Resource Sharing

Cross-origin resource sharing is similar to cross-domain policy files in the Flash word, but they are done through HTTP headers. The specification defines several different headers, however the only one I’ve needed so far is the response header Access-Control-Allow-Origin. Allowing my server to share resources with my local machine was as easy as adding the following line of PHP code before writing to the output buffer:

header('Access-Control-Allow-Origin: http://seeker.home');

(Seeker is the name of my development machine, named after the excellent Jack McDevitt novel.)

Of course, once I move the client-side portion of my application (the HTML, JS, and CSS files) to my server, I can delete or comment this line out since the application will be served from the same domain from which it needs to request data. In the meantime, however, it’s made local development much easier.

Cross-origin resource sharing is part of the XMLHttpRequest Level 2 specification, and is supported in all modern browsers.

7:20 PM Comments (0) Permalink
November 30, 2011

Adding prependChild to Element

If you’ve ever done much DOM scripting, you have almost certainly used the appendChild function on Element. For instance, you might have done something like this:

var hello = document.createElement('p');
hello.innerText = 'Hello, world!';
document.getElementById('myDiv').appendChild(hello);

Nice and easy, but what if you want to prepend the child rather append? You could do this:

var hello = document.createElement('p');
hello.innerText = 'Hello, world!';
var myDiv = document.getElementById('myDiv');
myDiv.insertBefore(hello, myDiv.firstChild);

Or, you could just add a prependChild function to Element, like this:

Element.prototype.prependChild = function(child) { this.insertBefore(child, this.firstChild); };

Just make sure that the code above evaluates early on in your application initialization, and start prepending all you want. (Of course, if you’re using jQuery, prepend is already well in hand.)

4:45 PM Comments (0) Permalink
November 11, 2011

My Thoughts on Flash and HTML (as Expressed in an Email to “Tech News Today”)

I’m a big fan of the video and podcast Tech News Today. It’s one of the best technology shows I know of, and I seldom miss an episode. As some of you know, I sent them an email yesterday about our recent announcements around Flash and HTML, and they were kind enough to read some if it on-air. It was way too long for them to read in its entirety, so I figured I’d post the whole thing here.

As someone who has worked on the Flash Platform at Adobe for the last nine years, I just wanted to provide some additional context around yesterday’s announcement. Your coverage was very good, so no complaints, but I feel like it’s worth emphasizing a few things.

Part of Adobe’s story is enabling cross-platform solutions, but since Flash has never been supported on iOS, we weren’t able to deliver on that vision in the context of mobile browsers. With mobile browsers as good as they are now (the ICS browser looks amazing, and mobile Safari has always been awesome), it just makes more sense to use HTML.

In the context of installed applications, however, our story is stronger than ever. We recently released AIR 3 which is an extremely solid option for delivering installed applications through app stores across devices. Installed mobile applications is an area where we have been very successful delivering on our cross-platform vision, so that’s where we’re going to invest. Additionally, I think that model more closely matches the way we use our devices; I think mobile browsers are primarily used for accessing content, and the tendency is to use installed apps for more interactive content like applications and games.

Another point I want to make is in response to Sarah’s comment yesterday about Flash working better on some devices than others. That’s true. Getting Flash to work consistently across all the chipsets that we support (and with all the different drivers out there — some of which are better implemented than others) is a huge amount of work, and requires a lot of engineering resources. At some point, we had to ask ourselves if we wanted to be the kind of company that continues to use resources to pursue something we weren’t convinced made sense just because it’s what we’ve always done, or if we wanted to be more forward thinking. I think we absolutely made the right decision.

It’s also worth pointing out that we’re still investing heavily in Flash in the areas where it makes more sense like installed mobile and desktop applications, and the desktop browser. Specifically, the Stage3D APIs we introduced in AIR 3 are going to provide an in-browser gaming experience like nobody has ever seen (look for videos of Unreal running in the browser), and the new APIs for hardware accelerated video are going to mean higher quality video that uses less CPU and battery. These are areas that HTML5 has not yet fully addressed, so Flash can lead the way. We will continue to use Flash for doing things that HTML can’t, and for the things that HTML can do, we will embrace it.

That brings me to my last point: I think there’s this perception out there that Adobe dislikes HTML, and that yesterday was somehow a bitter concession. As someone inside the company, I can tell you that there are a lot of us who are very excited about what we can do with HTML5. Personally, I’ve been researching and working on HTML projects for quite some time at Adobe, and I’ve been working with a lot of very smart people who are as passionate about it as I am. There are definitely people out there (both inside Adobe and outside) who are passionate just about Flash, but I think it’s more accurate to say that the overwhelming majority of us are simply passionate about the web, and about building awesome experiences. Flash has always been about providing functionality that HTML couldn’t, however now that HTML5 can provide a lot of that functionality, we’re going to have a lot of fun seeing what we can do with it.

So in summary, look for Adobe to continue to push Flash forward in areas that HTML doesn’t yet address, to push HTML forward with contributions to WebKit and tooling, and to provide cross-platform solutions in whatever technology makes the most sense.

If you want to hear it read on-air, it’s at the 45:00 mark in the video below.

9:32 PM Comments (7) Permalink