Skip to content

Instantly share code, notes, and snippets.

@stephancom
Created June 4, 2011 19:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephancom/1008248 to your computer and use it in GitHub Desktop.
Save stephancom/1008248 to your computer and use it in GitHub Desktop.
unobtrusive rollover coffeescript vs original
// purpose of script is to handle rollovers unobtrusively, e.g.
// <img src='original.png' data-rollover='rolled.png'>
$(function(){
$('img[data-rollover]').live('mouseover', function(){
if($(this).data('rollover-original') == null) {
$(this).data('rollover-original', $(this).attr('src'))
}
$(this).attr('src', $(this).data('rollover'))
}).live('mouseout', function(){
$(this).attr('src', $(this).data('rollover-original'))
})
})
# coffeescript version
# eh, it's not that much nicer. Maybe if I could replace '$(this)' with something like '$@' ?
# but then it starts looking like perl :(
$ ->
$('img[data-rollover]').live 'mouseover', ->
$(this).data 'rollover-original', $(this).attr('src') unless $(this).data('rollover-original')?
$(this).attr 'src', $(this).data('rollover')
.live 'mouseout', -> $(this).attr 'src', $(this).data('rollover-original')
@TrevorBurnham
Copy link

Hey, if you'd rather type function() { } instead of ->, be my guest. :)

I think where CoffeeScript really shines is in large applications, where classes provide a very neat way of organizing your code (even if you're not totally into classical OO). I hope you'll keep that in mind in your front-end coding endeavors.

@stephancom
Copy link
Author

stephancom commented Jun 5, 2011 via email

@stephancom
Copy link
Author

It is worth noting that I am now a coffeescript convert - today I would no sooner use plain JS instead of coffeescript than I would use html or erb instead of haml or slim.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment