Archive for the ‘Web Development’ Category

Chrome Developer Tools – monitorEvents

Tuesday, October 4th, 2011

I have been playing with the Chrome Developer Tools lately. Here is a cool feature I didn’t know about.

There are many times I have run some code in the console simply to bind to an event and simply log the result.

$("body").bind("click mousedown", function(e) {
    console.log(e);
});

There is a built in alternative called monitorEvents. Here is a quick demo on how to use it:

Inspect an element (see screenshot). Now that it has been inspected, there is a $0 variable available in the console.

Instead of that extra bind, you can just type this into the console:

monitorEvents($0, 'mouse')

Which, if you have the body selected in the Elements panel, is equivalent to typing:

monitorEvents(document.body, 'mouse')

OK, now that you can see all these events in the console and you have tracked down your issue, you probably want them to stop! Luckily, there is an unmonitorEvents function to do this.

unmonitorEvents(document.body)

You can also use ‘key’ instead of ‘mouse’ if you are tracking key events. There are actually a number of second parameters, but the support between Firebug and Devtools varies.

Possible Arguments For Firebug’s monitorEvents

Via the Firebug command line API

composition contextmenu drag focus form key load mouse mutation paint scroll text ui xul

Possible Arguments For DevTools monitorEvents

Thanks to Paul Irish dropping by in the comments and linking to the source, we now know all the officially supported DevTools keywords:

mouse key touch control

Map of Events for DevTools monitorEvents:

mouse:  “mousedown”, “mouseup”, “click”, “dblclick”, “mousemove”, “mouseover”, “mouseout”, “mousewheel” 
key: “keydown”, “keyup”, “keypress”, “textInput”
touch:  “touchstart”, “touchmove”, “touchend”, “touchcancel”
control:  “resize”, “scroll”, “zoom”, “focus”, “blur”, “select”, “change”, “submit”, “reset”
no arguments: all of the above + “load”, “unload”, “abort”, “error”, “select”, “change”, “submit”, “reset”, “focus”, “blur”, “resize”, “scroll”, “search”, “devicemotion”, “deviceorientation”

Chrome Developer Tools Colorpicker Concept

Monday, October 3rd, 2011

I always thought it would be awesome to have a colorpicker in browser developer tools. Who wants to guess at hex colors or open up a separate program just to get a color code? Apparently I’m not the only one who thinks a colorpicker inside the developer toolbar would be nice.

So, I did some reading on how to contribute to developer tools and integrated my spectrum colorpicker into the color swatch button.

Check out the demo in this video:

Unable to display content. Adobe Flash is required.

Of course, I don’t want to get rid of the swatch button (it usually rotates through color formats if you click it which can be useful), so the UI could use some work. Still, this functionality makes picking colors a lot easier, I think.

Keep Aspect Ratio With HTML and CSS

Wednesday, September 28th, 2011

When working on my javascript colorpicker, one of the things I thought would be really cool is if you could resize it and have the colorpicker automatically respond to different widths. When I first made it, I had basically defined static widths with the thought that there could be different themes (small, normal, large) which defined different widths.

This turned out to be a pain, since you had to manually figure out what each width needed to be for the total size. To complicate things further, I wanted to have a different percentage width when accessing the colorpicker via an iPhone. I found that the hue slider was a little too small to accurately slide with the touch interface, so I wanted it to take up more of a percentage of the total width. I’m can be lazy about calculating widths in CSS, so I went off looking for a different way to do this.

Aspect Ratios

Why couldn’t I just use percentage widths? Because the left portion of the colorpicker needs to be a square – or else the gradients for saturation and value just look weird and don’t really map up 1:1. I did some searching and found a CSS workaround to keep the aspect ratio of a fluid element by ansciath. The meat of this trick is that according to the spec for margin-top, a percentage refers to the width of the containing block, not the height. This post got me much of the way there, but I had to include a couple of fixes for IE and ways.

The really nice part about using this technique is that it makes spectrum extremely easy to skin in your own CSS. Check out ColorStash for an example of this. Using media queries and max-widths, I can change the width of the colorpicker as the browser resizes to get some really responsive behavior on a UI control (colorpicker) that has typically been very static.

Demo

See the demo of the aspect ratio and media query. Try resizing your browser window to under 480px width to see the switch happen. Here is the full source code for the demo.

Below is a snippet showing the basic HTML/CSS needed for this technique:

<div class='container'>
    <div class='outer'>
        <div class='fill'></div>
        <div class='inner-top'>
            <div class='square'>Always a square</div>
            <div class='right'>% width</div>
        </div>
    </div>
    <div class='bottom'>
        Bottom
    </div>
</div>
.outer {
  position:relative; 
  width: 100%;
  display:inline-block;
}
.inner-top {
   position:absolute; top:0; left:0; bottom:0; right:0;
}
.square {    
    position: absolute;
    top:0;left:0;bottom:0;right:20%;
    background:orange; 
}
.right {
    position: absolute;
    top:0;right:0;bottom:0;left:83%;
    background: purple;
}
.fill { 
    *height: 80%;
    margin-top: 80%;  /* Same as square width */
}
@media (max-width: 480px) {
    .square { right: 51%; background: blue; }
    .right { left: 51%; }
    .fill { margin-top: 49%; } 
}

Create a hue slider with CSS gradients

Thursday, September 8th, 2011

Yes, That Is A Fancy Way Of Saying Rainbows

For most browsers, you can use the linear gradient vendor property with multiple color stops. In IE, the filter property does not support color stops, so we have to fake it with 6 divs, each with a single color stop gradient. It works in Internet Explorer, back to version 5.5.

I made this while working on my JavaScript colorpicker, Spectrum. Check out the hue slider gradient demo on jsfiddle, where you can play with the source.

#hue {
    height:200px;
    width: 40px;  
 
    background: -moz-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
    background: -ms-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
    background: -o-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
    background: -webkit-gradient(linear, left top, left bottom, from(#ff0000), color-stop(0.17, #ffff00), color-stop(0.33, #00ff00), color-stop(0.5, #00ffff), color-stop(0.67, #0000ff), color-stop(0.83, #ff00ff), to(#ff0000));
    background: -webkit-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
    background: linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
}
 
#ie-1 { 
    height:17%; 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0000', endColorstr='#ffff00');
}
#ie-2 { 
    height:16%; 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff00', endColorstr='#00ff00');
}
#ie-3 { 
    height:17%; 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00ff00', endColorstr='#00ffff');
}
#ie-4 { 
    height:17%; 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00ffff', endColorstr='#0000ff');
}
#ie-5 { 
    height:16%; 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0000ff', endColorstr='#ff00ff');
}
#ie-6 { 
    height:17%; 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff00ff', endColorstr='#ff0000');
}

Not exactly pretty, but it is one way to get multiple color stops in Internet Explorer working.

What I want in a JavaScript colorpicker

Sunday, September 4th, 2011

I have been wanting to add colorpickers in a couple of projects recently, and was not happy with the options. Just search JavaScript Colorpicker and you’ll see what I mean. It got me thinking about what I wanted out of a colorpicker.

No Images!

It is pretty well known that you should limit the number of images that your web page requests for performance reasons. Some of these, including the eyecon.ro picker, which is the first that shows up when searching ‘jQuery colorpicker’, require a ton of images (27, in fact). This is overkill. Why can’t it be skinned with HTML/CSS?

Reasonable defaults

I found myself having to dig through the source code of various colorpickers in order to get them to act how I wanted. Maybe my experience on this is unique, but once I wanted to actually script behavior to go along with the picker (think – a template editor for an online portfolio), it became painful quickly.

Browser Support

It needs to support all major browsers (even IE). Ideally it could also support mobile devices.

Drop in

Didn’t want to have to download zip folders, place a bunch of images in my project and modify css files to point to the correct image path, etc. I just want to include a single JavaScript file, and a single CSS file, and be done.

Anything Like This?

I did find the nifty FlexiColorPicker, which accomplishes the no images goal with SVG and VML. It seems very nice, but didn’t have some of the features I wanted (dragging around the hue slider and picker didn’t actually work). I’m glad I found it, as I did use some of the gradients as a starting point with my CSS gradients.

Spectrum – My JavaScript Colorpicker

I have done a fair amount of color manipulation work while building a color scheme generator in a theme editor. I also have made a JavaScript color micro framework for parsing and conversion, called TinyColor. This is designed to allow a wide range of input and output (named colors, hex, rgb, hsl, hsv).

So, I decided to try my hand at this, and made the spectrum JavaScript colorpicker.

It works in all major browsers (tested in Safari, Chrome, Firefox, IE 7+, iOS, Opera). It uses IE’s propriety gradient filter (with some hacks for the hue slider – see .spectrum-ie-1 through 8 in spectrum.css. It should even work in iPhone and iPad – let me know if you have one and can double check that for me over on the demo page :). It is still in early stages, but I would love if I could get some feedback on the UI and desired functionality.

Demo

Head over to the current project page to try out the demo and see the docs.

It currently requires jQuery, but I have been trying to write the code to make it possible to remove that dependancy.

bindWithDelay jQuery Plugin – Now With Throttling

Friday, May 13th, 2011

I decided to add in throttling functionality to the jquery bindWithDelay plugin. This is a nice feature that didn’t require very many changes to the code (see the: diff).

What is throttling?

Imagine you are scrolling down a long page for 3 seconds and you have bindWithDelay running with a timeout of 1000ms. By default, your event will only fire a second after you have completely finished scrolling. If you have the optional throttling on, it will fire once per second during the scrolling – a total of 3 times instead of 1.

Checkout the throttling demo to see what it is doing.

wordsolver.js

Thursday, February 10th, 2011

I was playing around with unscrambling words recently, and decided to implement a solver in JavaScript. I called it wordsolver.js.

Demo

There is a wordsolver demo on my site. Try typing in URESMTA or something to see all the words that get unscrambled.

Code

All code can be found in the wordsolver repository on github. In particular, here is the file that does all the heavy lifting. It is all available under the MIT license.

How does it perform?

Smoother than I expected it to. The load time for the dictionaries can be pretty slow (they are anywhere from 1.7MB to 2.6MB depending on the dictionary), but once it loads, it finds words pretty fast and tries to cache results. Warning: it will probably crash an iPhone while trying to load the dictionary array into memory

Como Rich Web Canvas Presentation

Thursday, December 16th, 2010

I presented at the Columbia MO web developer meetup on 12/15/2010. I talked about HTML canvas and JavaScript FileReader, Instant Sprite, JavaScript image processing, and other topics.

The slides for the talk are available at http://briangrinstead.com/canvasslides.

More details about the monthly meeting.

Safer JSONP

Monday, November 29th, 2010

I read a nice write up on on JSON and JSONP by Angus Croll. He provided a sample implementation of a safe JSONP library.

The library is concise and does the trick for a single connection, but I found it didn’t handle multiple connections. It would overwrite a single global callback, so if you had connections of varying speeds, you would undoubtedly get errors. For instance, “Request 1″ is very slow, and “Request 2″ gets finished before it. When “Request 1″ gets finished, it uses the callback for “Request 2″. This actually happened the first time I loaded it up and ran it. Not good.

Here is a simple updated version that takes care of that particular problem.

/*
An implementation of: http://javascriptweblog.wordpress.com/2010/11/29/json-and-jsonp/
that handles multiple connections at once (don't want to replace the global callback if second
request is sent after the first, but returns before.
*/
 
(function(global) {
 
var evalJSONP = function(callback) {
	return function(data) {
		var validJSON = false;
		if (typeof data == "string") {
			try {validJSON = JSON.parse(data);} catch (e) {
				/*invalid JSON*/}
		} else {
			validJSON = JSON.parse(JSON.stringify(data));
			window.console && console.warn(
				'response data was not a JSON string');
		}
		if (validJSON) {
			callback(validJSON);
		} else {
			throw("JSONP call returned invalid or empty JSON");
		}
	}
};
 
var callbackCounter = 0;
global.saferJSONP = function(url, callback) {
	var fn = 'JSONPCallback_' + callbackCounter++;
	global[fn] = evalJSONP(callback);
	url = url.replace('=JSONPCallback', '=' + fn);
 
	var scriptTag = document.createElement('SCRIPT');
	scriptTag.src = url;
	document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
};
 
})(this);

To test it out:

var obamaTweets = "http://www.twitter.com/status/user_timeline/BARACKOBAMA.json?count=5&callback=JSONPCallback";
saferJSONP(obamaTweets, function(data) {console.log(data[0].text)});
 
var reddits = "http://www.reddit.com/.json?limit=1&jsonp=JSONPCallback";
saferJSONP(reddits , function(data) {console.log(data.data.children[0].data.title)});

If you are really worried about multiple global objects JSONPCallback_1, JSONPCallback_2, etc – you could store them all in an array instead. Like this:

(function(global) {
 
var evalJSONP = function(callback) {
	return function(data) {
		var validJSON = false;
		if (typeof data == "string") {
			try {validJSON = JSON.parse(data);} catch (e) {
				/*invalid JSON*/}
		} else {
			validJSON = JSON.parse(JSON.stringify(data));
			window.console && console.warn(
				'response data was not a JSON string');
		}
		if (validJSON) {
			callback(validJSON);
		} else {
			throw("JSONP call returned invalid or empty JSON");
		}
	}
};
 
var callbackCounter = 0;
global.JSONPCallbacks = [];
global.saferJSONP = function(url, callback) {
	var count = callbackCounter++;
	global.JSONPCallbacks[count] = evalJSONP(callback);
	url = url.replace('=JSONPCallback', '=JSONPCallbacks[' + count + ']');
 
	var scriptTag = document.createElement('SCRIPT');
	scriptTag.src = url;
	document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
};
 
})(this);

Instant Sprite – CSS Sprite Generator

Friday, November 19th, 2010

I’ve been working on a project to make generating CSS Sprites faster and easier. It is called Instant Sprite, and available at http://instantsprite.com. You can drop the images right into the browser (or open them up in a file input) and it generates the sprite in the browser, with no file uploads. You can check it out and use some sample images provided if you don’t have any images available.

Instant Sprite uses HTML Canvas and the FileReader interface to read images from your hard drive – this prevents you from having to zip up all the images before passing them off to the sprite generator. You can also preview your changes to CSS tweaks in real time, so you don’t have to resubmit if the file match regex isn’t doing what you want.

I’d like to give credit to Aaron Barker for helping out with a lot of feedback and UI suggestions.

I made it for myself so that generating sprites was easier, but put it online because I think it might be useful to others, too.