2

I had a coffee code like this.

  $('.foo').hover \
    (-> $(this).css "cursor", "pointer"), \
    (-> $(this).css "cursor", "default")

And I want to apply this function to dynamically appended DOM, so I tried to delegate function by using on() like this.

As a example I referred this question

  $(document).on 'hover', '.foo', (event) ->
    $(this).css "cursor", "pointer" if event.type is "mouseover"
    $(this).css "cursor", "default" if event.type is "mouseout"

But this code doesn't work at all.

How can I apply the function to dynamically added elements?

Community
  • 1
  • 1
ironsand
  • 14,329
  • 17
  • 83
  • 176
  • 2
    [*The `.hover()` method binds handlers for both `mouseenter` and `mouseleave` events*](http://api.jquery.com/hover/) rather than `mouseover` and `mouseout`. Also, note that `.on()`'s support for `'hover'` was [*deprecated in jQuery 1.8, removed in 1.9*](http://api.jquery.com/on/#additional-notes). – Jonathan Lonowski Jan 31 '14 at 19:41

1 Answers1

1

I think you'll need to unbind and add the hover handler. Also, you don't need the line continuations if you're indenting (in this case).

$( -> 

  #debugger 

  addFooDiv = -> 
    div = $('<div class="foo">This is another foo div</div>') 
    $(this).parent().append(div)
    addFooHandler()

  onLeaveHandler = -> 
    $(this).css "cursor", "pointer"  
    $(this).css "background", "white"

  onEnterHandler = ->   
    $(this).css "cursor", "default"  
    $(this).css "background", "lightblue" # so it's real obvious

  $('.appendFoo').on('click', addFooDiv)

  addFooHandler = ->   
    $(".foo").unbind("hover") 
    $(".foo").hover(onEnterHandler, onLeaveHandler)

  addFooHandler()
)

http://plnkr.co/edit/JbQtqIOhg2AHBCuoHs4N?p=preview

Props to Sethen Maleno: https://stackoverflow.com/a/9827114/30946

Community
  • 1
  • 1
jcollum
  • 43,623
  • 55
  • 191
  • 321