Convert this jquery to coffee script?

I am not sure how to structure the following. This works great:

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

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

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

This returns an error - "unexpectedly." I tried other options, and most of the examples I found on the Internet do not use the format .on 'hover' (ev) ->.

+5
source share
3 answers

You cannot use on()for this if you want to connect both event handlers at the same time.

You need to use hover():

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

or even better using toggleClass()

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

jQuery toggle , , , :

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

. . , . , , , coffeescript.

-4
source

All Articles