Archive for the 'Javascript' Category


ReaderScroll: Google Reader Style Image Navigation With J-K Keys Bookmarklet

6

Shortly after posting ScrollMonkey I realized the same functionality could be implemented as a bookmarklet, obviating the need for GreaseMonkey, making it available to a lot more people. So here it is implemented as a bookmarklet.

To refresh your memory, the script does a very simple thing - it brings the next image to the top of the browser window so you can see it. You hit “j” to see the following image and “k” to go back to the previous.

To install, click and drag the ReaderScroll bookmarklet to your FireFox toolbar or right click on it if you’re using IE.

Once installed in your toolbar, you can enable it for any website you’re visiting by clicking on it in your toolbar. For example, go to any of these pages with lots of images and then click the bookmarklet. Then click anywhere on the page you’re viewing and hit the “j” key several times until the first large image is at the top of the browser window. Now you can navigate to the next image by hitting “j” again and go back to previous images with “k”.

The bookmarklet doesn’t have the disadvantages associated with the ScrollMonkey GreaseMonkey version; it’s only triggered when you click it, so no unnecessary overhead. It would still make sense to make it more generic so you could navigate to the next paragraph, heading, etc. With jQuery under the hood this would be easy to do and I’ll do it if there’s demand for it.

And thanks to FriendFeed from whom I stole most of the idea for the bookmarklet.

ScrollMonkey: Google Reader Style J-K Hotkeys For Image Paging And Centering

10

I’ve long wished for Google Reader style hotkeys (hitting “j” to move to the next item, “k” to go to the previous) to be available in more places. In particular, pages with many images are screaming for it - it’s just silly to keep messing with the scroll bar to get each image to line up properly in the viewable portion of the browser. If you don’t know what I mean go to any of these pages with lots of images and try to view each image. If you’re not frustrated with the scroll bar by the 3rd image you’re far more patient than I.

I finally found a few minutes to hack at it, and sure enough, it was quite easy to do with GreaseMonkey and jQuery.

The script does a very simple thing - it brings the next image to the top of the browser window so you can see it. You hit “j” to see the next image and “k” to go back to the previous.

Install GreaseMonkey and then install ScrollMonkey by clicking on it.

Once installed, go to any of the above pages with images, click on the page (to ensure the page is in focus), and hit the “j” key a couple of times until the first picture is at the top of the browser window. Now hit “j” again to go to the next image and “k” to go back.

The script is very simple and brain dead - I’ve made no attempt to make it intelligent. In particular, it’s active on every page and it downloads jQuery, which is probably more overhead than you want to have. In my case I typically have GreaseMonkey turned off and only turn it on when I need it, so it’s not much of a problem. It also looks at all images instead of attempting to find the large images of interest.

It would also be smart to generalize it to deal with anything - paragraphs, headings, etc - instead of just images.

And it’d be probably be nice to have it turn on via a hotkey instead of always being on, and it probably will interfere with any forms you’ll try to fill out.

But practically speaking none of these are problems I run into, so I’ll leave them for now and fix them if there’s any demand for it.

Give it a try and let me know what you think.

Here’s the code in its entirety, for those interested:


// Add jQuery
var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);  

 // Check if jQuery’s loaded
function GM_wait() {
	if(typeof unsafeWindow.jQuery == ‘undefined’) { window.setTimeout(GM_wait,100); }
	else { $ = unsafeWindow.jQuery; run(); }
}
GM_wait();  

function run() {
	var images = $(’img’),
		idx = -1,
		nimages = images.length;
	$(document).keypress(function (e) {
		// j == 106 ; k == 107
		if (e.which != 106 && e.which != 107) { return; }
		if (e.which == 106 && idx < nimages-1) { idx++; }
		if (e.which == 107 && idx > 0) { idx–; }
		var top = $(images[idx]).offset().top;
		unsafeWindow.scrollTo(0, top);
	} );
}

Javascript Inheritance

0

Javascript inheritance is another one of those topics that always escapes my mind, so I’m recording it here for future reference.

I tried to get into Crockford’s Prototypal Inheritance method but I like the plain-old prototype inheritance without the object.create better. It’s entirely possible that I’m not quite getting Crockford’s method and it’s advantages; feel free to enlighten me by leaving a comment.

Anyway, here’s what I’m going with: We’ll have a base class (actually an object) English that says “hello” and “goodbye”. We’ll have a Spanglish class (actually an object) that inherits from English and says “ola” instead of “hello” (over-rides the hello method), but keeps saying “bye” (inherits the bye method from English).

The Spanglish.prototype = new English(); line does the actual inheritance by setting Spanglish’s prototype to be an instance of English.


function English() {
	this.hello = function(){ return "hello"; }
	this.bye   = function(){ return "bye"; }
}

function Spanglish() {
	this.hello = function() { return "ola"; }
}
Spanglish.prototype = new English();

e = new English();
s = new Spanglish();

e.hello();   // prints "hello"
e.bye();     // prints "bye"
s.hello();   // prints "ola"
s.bye();     // prints "bye", inherited from English

Google Reader Style Hotkeys For Image Viewing

1

I frequently run into pages with loads of images (here’s one via Kedrosky, here’s another, and here’s yet another). Viewing these images involves a dance of scrolling or hitting space, then scrolling again to get the image lined up in the viewable part of the browser, and repeating over and over again.

The better user experience would be to have Google Reader style hotkeys that bring each picture into view, lining it up properly for easy viewing. You’d be able to hit “j” after viewing each picture to see the next. No more messing with the scrollbars.

I’m guessing a greasemonkey script to enable this with any page would be pretty straight forward to do. Anybody know if it already exists? If not, someone should do it.

TraceMonkey: It’s A Big Deal

0

Mozilla announces TraceMonkey, a just-in-time compiler for Javascript. If you’ve watched Steve Yegge’s talk on Dynamic Languages (transcript) you’ve already had a taste of what the future could look like for dynamic languages - namely, performance on par with today’s low level languages.

Javascript started as an ugly language but has been steadily shedding its bad parts and adopting a beautiful functional style. With the performance piece figured out and a tremendously large number of installations and runtimes (just about every browser in existence has a Javascript engine), it could become the most important programming language of the near future.

YUI 3.0 with jQuery Style Chaining and Selectors

0

I started my foray into the world of Javascript with YUI, later found jQuery, and over time have been moving more and more to jQuery. Selectors and chaining are fruity and delicious and encourage a nice functional programming style.

YUI, however, does offer a bunch of nice, well tested UI components which are generally lacking in jQuery, leading me to typically use both YUI and jQuery together in an unattractive Frankenstein way.

Therefore I’m excited to see YUI’s move towards jQuery style selectors and chaining with their 3.0 preview release. It’s also very nice that they’ve abstracted away javascript file loading with the module concept - with YUI 2.x you have to do a which-files-do-I-need dance and load each of the multitude of files separately. With 3.x you “.use” the module you need (say “dd-drag”) and YUI intelligently loads the required files in a single HTTP request.

This is good stuff. I’m really enjoying jQuery so it’ll be tough to completely jump ship, but with the new additions I could see doing a lot more with YUI.

Best Packing Method for jQuery for iPhone?

0

I thought I was all caught up with my packing-fu for my javascript, but a quick look at YSlow on a friend’s computer revealed I had some oddly packed version of jQuery that was 56K instead of the 30K packed version from the jQuery site. Once spotted (thanks YSlow!) this was quickly remedied.

Now I’m wondering what the best packing method for jQuery on iPhone is, since size and performance are even more important there. gzip or no gzip? Which packer?

JavaScript-Only iPhone Apps?

0

Is there a way to write iPhone apps that can be distributed via the AppStore without writing Objective-C / Cocoa code? I’m perfectly happy writing happy HTML, CSS, and JavaScript, but don’t want to get too deep into Apple proprietary languages and technologies.

Basically I just want the HTML/CSS/JavaScript app I have packaged so it can live offline on the iPhone, have network access, and use the local SQLite instance. I’ve looked at the SDK videos, the docs, and everything else I could find, but they all seem focused on writing Objective-C.

If that’s not possible, is there a bare-bones skeleton app that simply embeds safari and renders files stored on the iPhone?

jQuery serializeArray: Why Not An Associative Array?

3

I’m trying to examine and modify form variables from jQuery by catching the submit event. jQuery has a serializeArray method that hands you the form variables in a nice array. For example:


	$('#someform').submit( function() {
		$.post("/some/url/", $(this).serializeArray(),
			function(data){
			    console.log(data);
			}, "json");
		return false;
	 } );

This is great, but the result of serializeArray is an integer indexed array whose values are (key,value) pairs. Eg.


	var data = $(this).serializeArray(),
	console.log( data[0] );
>> output: Object name=somename value=537

I’m wondering why the array looks like this, instead of being a dictionary (associate array, hash, or whatever you want to call it) such that the keys are “name”s and values are “value”s. Eg.


	var data = $(this).serializeArray(),
	console.log( data.somename );
>> output: 537

Anybody know the answer?

Javascript Is The Guy With The Thing

0

Man with ShovelIn most programming languages (Java, C, Python, Perl) I’m generally thinking “I’ll put this thing on this shelf here, then I’ll do x, then I’ll pick up that thing, do some work on it, put the result over here,” and so forth.

With Javascript, particularly when used correctly, which for me means in the Way Of JQuery, the thought process is more like “When some event happens, this guy will wake up and he’ll know what to do. He’ll remember his name, what he was supposed to work on, and he’ll be carrying his own tools. He might get blocked at some point, but then he’ll just wait around and when he’s ready to go he’ll remember who he is, what he was doing, and how far along doing it he was. And when he’s done he’ll go away and along with him will go his tools and any other mess he made”.

Javascript is a lot more “guy with the thing” thinking instead of “what’s on this shelf here?” thinking. I guess that’s called closures, or something like that. Anyway, I’m liking it.

Photo by St-Even.

Javascript Array Deferencing?

1

I have an array, say:


var pieces = [2008, 5, 19, 13, 49];

I’d like to create a date based on this; the equivalent of:


new Date( 2008, 5, 19, 13, 49 );

Is there a way to do that in Javascript? Can I dereference the array in my date create call? I’d prefer to avoid eval.

Beautiful Treemaps and Visualization for Javascript

0

Next sign

The Javascript Information Visualization Toolkit looks very good. Look at how beautiful the treemap and hypertree examples are.

Btw, I’m voting Joshua Schachter for best link blog.

How To Dynamically Select Part of a jQuery Call Chain

3

Updated, thanks to Simon Willison:

Say you’d like to pick part of your jQuery call chain dynamically - for example, to removeClass for many elements, but addClass to one special element. Here’s how you do it:


var myfunc = some_condition ? 'addClass' : 'removeClass';
$('#someid').html('something')[myfunc](’some_class’);

The first line selects the function name as a string. The second line calls the ‘html’ function (it could be any function; html is just the example in this case), followed by the function with the selected name (addClass or removeClass in this case).

You’d probably use this in the context of a loop, eg:


for (var i=0; i<10; i++) {
    var myfunc = some_condition ? 'addClass' : 'removeClass';
    $('#something'+ i).html('sample text ' + i)[myfunc]('selected');
}

Handy Javascript Scoping Trick

0

Neat Javascript function scoping trick from Dustin Diaz, master of cool Javascript tricks. His Javascript Video Tutorials were the first time I was exposed to proper Javascript (Justin, do some more!).

Here’s the trick:


var o = 'hello world';

(function() {
  alert(this);
}).call(o);

And why is this neat? Because it lets you avoid the “that = this” funkiness (if you’ve had to do it you know what I’m talking about). Read Justin’s post for actual info.

HTML ID Syntax

1

From W3C HTML Recommendation:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (”-”), underscores (”_”), colons (”:”), and periods (”.”).

(Noting here because I always forget and have to look this up)

Javascript Style Reference

0

Writing proper Javascript is not quite intuitive (at least for me), so I’m recording these two patterns for creating a module and a class here for future reference:

myModule = function () {

    var myPrivateVar;
    var myPrivateMethod = function () { }

    return  {
        myPublicProperty: "something",
        myPublicMethod: function () { }
    };
}();

function myClass() {
	var  private_var = 1;
	var  private_function = function() { alert("private!"); };
	this.public_var    = "something";
	this.public_method = function() { alert(private_var); private_var += 1; }
}

var myInstance = new myClass();