tags:

views:

124

answers:

3

It just crossed my mind that it would be extremly nice to be able to apply javascript code like you can apply css.

Imagine something like:

/* app.jss */
div.closeable : click {
  this.remove();
}

table.highlightable td : hover {
  previewPane.showDetailsFor(this);
}

form.protectform : submit { }
links.facebox : click {} 
form.remote : submit {
   postItUsingAjax()... }

I'm sure there are better examples.

You can do pretty similar stuff with on dom:loadad -> $$(foo.bar).onClick (but this will only work for elements present at dom:loadad) ... etc. But having a jss file would be really cool.

Well, this has to be a question, not a braindump... so my question is: is there something like that?

Appendum

I know Jquery and prototype allow to do similar things with $$ and convenient helpers to catch events. But what I sometimes dislike about this variant is that the handler only gets installed onto elements which have been present when the site first got loaded.

+2  A: 

You should look into jQuery. I don't have the luxury of using where I work, but it looks like this:

$("div.closeable").click(function () {
    $(this).remove();
});

That's not too far removed from your first example.

Joel Coehoorn
$('div.closeable').bind('click',function(){this.remove();}); would work... presuming that the actual DOM elements had a .remove() method attached to them.
scunliffe
to work completely like CSS does... you'd want to use the .live() option to capture future elements created.
scunliffe
A: 

Have a look at jquery. You could have a .js include file that you add to all of your pages and get something very close to what you are describing.

The biggest pitfall would be performance.

Jimmie R. Houts
+7  A: 

The closest thing I've seen to what you're talking about are jQuery's Live Events:

http://docs.jquery.com/Events/live

They basically will pick up new elements as they're created and add the appropriate handler code you've assigned.

Gabriel Hurley
Exactly. This addresses both the original question and the appendum. Live will re-evaluate the selectors and apply the associated javascript each time the DOM changes.
Justin Johnson