Saturday, July 30, 2011

Bookmarklet: Scroll to the last new Tweet on Twitter

Drag this link: Last New Tweet to your bookmarks toolbar for a bookmarklet that will automatically scroll you to the last new tweet in your Twitter feed.

This would be more useful as a Greasemonkey script, but bookmarklets work for more browsers. Here's the code behind it:

(function() {
  var t = $('.last-new-tweet');
  scroll(0, t.offset().top + t.height() - $(window).height());
})();

There are some interesting things in these few lines of code that are worth pointing out. That $() business is jQuery, a really great JavaScript library for writing compact, powerful, cross-browser JavaScript. I can use it in this bookmarklet because Twitter already uses it, so the library is already loaded. To (perhaps dangerously) oversimplify, $() lets you "select" page elements by class ($('.last-new-tweet')), reference ($(window)), id, and others, giving you a slew of useful functions (offset(), height(), etc) to query and manipulate them.

The other fascinating thing here is the immediate calling of an anonymous function. The basic syntax of this construct is:

(function (){statement;})()

In essence, a function is created, called, and discarded, all in one statement. This is useful when you specifically do not want a return value, or when you need to fit multiple statements into one statement.

Monday, July 18, 2011

Google site search bookmarklet

Drag this link: Search this site to your bookmarks toolbar for an instant site search button. Here's the code, prettified:

function f() {
  var q=prompt('Search for');
  if (q!=null) {
    location.href='http://google.com/search?q=site:'
      + location.host + '+' + encodeURIComponent(q);
  }
}
f();