user419017
user419017

Reputation:

Translate this jquery into coffee script?

I'm unsure how to structure the following. This works fine:

  $('.hover li').on 'hover', (ev) ->
    $(this).addClass('active')

I know I can use 'toggle' instead of 'addClass', but for other reasons I need a handler out function passed. So I tried this:

  $('.element').on 'hover', (ev)
    -> $(this).addClass('active'),
    -> $(this).removeClass('active')

This returns an error - 'unexpected ,'. I've tried other variations, and most of the examples I've found online do not use the .on 'hover' (ev) -> format.

Upvotes: 5

Views: 6556

Answers (3)

Niko
Niko

Reputation: 26730

You cannot use on() for this if you'd like to attach both event handlers at a time.

You need to use hover():

$('.element').hover(
  (ev) -> $(this).addClass 'active'
  (ev) -> $(this).removeClass 'active'
)

or even better, utilizing toggleClass()

$('.element').hover (ev) -> $(this).toggleClass 'active'

Upvotes: 8

iHiD
iHiD

Reputation: 2438

jQuery's toggle function takes two functions, which I think is what you're after:

$('.element').toggle 'hover', 
    (ev) -> 
        $(this).addClass('active')
        # Do other stuff...
    (ev) -> 
        $(this).removeClass('active')
        # Do other stuff...

Upvotes: 1

Kevin Sjöberg
Kevin Sjöberg

Reputation: 2254

$('.element').on 'hover', (ev) ->
  $(this).addClass('active').removeClass('active')

should do it. Although I don't get it. Your adding the class active and then removing it. Nevertheless, the above code is valid coffeescript at least.

Upvotes: -4

Related Questions