user419017
user419017

Reputation:

Coffeescript live toggle

How do I turn this into a live jquery toggle (coffeescript)?

$('.link').toggle(
  -> $(this).text('less'); $('.entry').css('height', 'auto'),
  -> $(this).text('more'); $('.entry').css('height', '300px')
)

I have tried wrapping this in a live function, but then it only triggers the first event, and will not toggle back.

Upvotes: 1

Views: 1346

Answers (1)

Mark
Mark

Reputation: 5720

Have you tried using .on, I'm assuming .link is inserted into the DOM dynamically, correct?

var hasToggle = false

$('body').on('click', '.link', (e) ->
  unless hasToggle
    $(@).toggle(
      -> 
        $(@).text('less')
        $('.entry').css('height', 'auto')
      ->
        $(@).text('more')
        $('.entry').css('height', '300px')
    )
  hasToggle = true
)

I think the reason it wasn't working is because everytime you click on .link with .on or .live its re-initializing a new .toggle event, so you're always going to call the first function in .toggle. If you set the event once for .toggle the first time a user clicks on it that may solve your problem.

Upvotes: 1

Related Questions