Posts Tagged ‘javascript’

jQuery UI CDN Boilerplate

Tuesday, December 13th, 2011

I always forget these links, and they are surprisingly hard to find. Here is a quick markup skeleton to throw together for prototypes using jQuery UI.

<!doctype html>
<head>
  <title></title>
 
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
  <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css" />
 
  <style type="text/css">
    #draggable {
		background: orange;
		width: 100px;
		height: 100px;
	}
  </style>
 
  <script type='text/javascript'>
	$(function() {
		$("#draggable").draggable().resizable();
	});
  </script>
</head>
 
<body>
<div id='draggable'>drag!</div>
</body>
 
</html>

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 ran some code like this:

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

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')

You can also use ‘key’ instead of ‘mouse’ if you are tracking key events. There are actually a number of second parameters, via the Firebug command line API. Note: not all of these seem to be supported by Chrome dev tools. Here they are:

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

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%; } 
}

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

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.

filereader.js – A Lightweight FileReader Wrapper

Sunday, November 14th, 2010

I am working on project that needs to read local files. This relies on the FileReader interface, and I couldn’t find any JavaScript libraries to help out with common usage for this, so I made one.

FileReader is a JavaScript interface that allows you to read local files as binary. This is available in supported browsers when a user drags and drops files into a browser window or selects files from an input with a type of file. See the FileReader specification for more information.

filereader.js is a wrapper for accessing this functionality. It can be called using:

FileReaderJS.setupInput(fileInput, opts);
FileReaderJS.setupDrop(dropbox, opts);

If you use jQuery, you can access these calls with:

$("#fileInput").fileReaderJS(opts);
$("#dropbox").fileReaderJS(opts);

To see the full range of options and functionality, view the readme.

filereader.js is available under the MIT License. See the full filereader.js code or the single file raw javascript source on github.

You can see an example project using filereader.js on Instant Sprite, a browser based CSS Sprite Generator that I am working on. Try dragging images onto the body, or clicking to add multiple image files to see what is possible.