Justin
Justin

Reputation: 641

jQuery Bind Toggle in Loop

I'm trying to bind click events via loop.

This works fine as long as I reference relative to the original bind (using this). Problem is, it is unrealistic use this since the elements I'm toggling are in a separate part of the DOM.

Results, line 4 will always reference "image" in this situation.

Coffeescript:

for name in ["contact", "kws", "image"]
  $("#expand-#{name}").bind('click', ->
    $(this).toggleClass("icon-plus-sign").toggleClass("icon-minus-sign")
    $(".#{name}-expander").toggle()
  )

Sadly, all I figure is to repeat code.

Thanks, Justin

Upvotes: 1

Views: 249

Answers (1)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263047

If I understand your question correctly, you have a variable scope problem. name will always be the last value assigned by the time your handlers run.

Coffeescript provides the do keyword to generate a self-calling closure and give the appropriate scope to name:

for name in ["contact", "kws", "image"]
    do (name) ->
        $("#expand-#{name}").bind('click', ->
            $(this).toggleClass("icon-plus-sign").toggleClass("icon-minus-sign")
            $(".#{name}-expander").toggle()
        )

Upvotes: 1

Related Questions