Bookmarklets are Fun
May 16th, 2005There has been much ado about Greasemonkey lately, and rightly so. Mark Pilgrim even wrote a book about it. I’ve found that Greasemonkey is a good way to learn a little Javascript and a bit about how to monkey around with the DOM.
That sounded kinky.
Anyway.
It seems to me that the way to learn Javascript is just to continually learn little tricks, bit by bit. (I’ve not been able to find any readable books that try to take a more high-level approach, although this essay is pretty informative.)
So here’s one I learned tonight, so I’m writing it down to remember. It’s very simple.
In css, if you want to give the body of your document margins, you can use a rule like this:
body { margin-left: 25%; margin-right: 25%; }
(Yes, I know, there’s some kind of shorthand “clock” notation for css margins, but I can never remember how it works. You get the point.)
It turns out that assigning a css rule in Javascript is quite easy:
document.body.setAttribute('style','margin-left:25%; margin-right: 25%');
I believe that document.body is unusual in that it’s sort of a “built-in” reference — if you wanted to a apply a style rule to any other node (say, a div), you’d have to get a reference to it first and then call .setAttribute on the reference.
But that’s all there is to it: the second argument is a string with whatever css you want to apply. And here it is as a bookmarklet:
try it → make skinny
(I should add, by the way, that I usually use this thing on “print” versions of news articles, like this one.)
Jesse Ruderman gave me some corrections for this code. The correct way to adjust the style of an element isn’t to use
document.body.setAttribute('style','margin-left:25%;margin-right:25%');
Rather, one sets the style directly, like this:
document.body.style.marginRight = "25%" document.body.style.marginLeft = "25%"
Note that the positioning is notated in camel case, from margin-left to marginLeft.
So here’s a better version:
try it again → make skinny
argh… I managed to break this, for the moment… fix upcoming.