I'm trying to programmatically create some javascript buttons to toggle visibility on the page (for snappy tag filtering). This works for one tag:
trigger = ".sales-focus-btn"
target = ".sales-focus"
jQuery ->
$(trigger).toggle ->
$("#primary-content").find('.container').hide()
$("#primary-content").find(target).show()
, ->
$("#primary-content").find('.container').show()
Is it possible to do something similar in coffeescript, but with arrays, e.g.
trigger = [
".sales-focus-btn"
".service-focus-btn"
".other-focus-btn"
...
]
target = [
...
]
Is it possible to loop over and create a toggle for each type of tag?
UPDATE
Yes it's possible. Use the form:
myFunction = (el) -> console.log el
myFunction elem for elem in array
Of course it's possible:
content = $('#primary-content')
container = content.find('.container')
tags = [
'.sales-focus'
'.service-focus'
'.other-focus'
]
$.each tags, (tag) ->
target = content.find(tag)
$(tag + "-btn").toggle ->
container.hide()
target.show()
, ->
container.show()
Remember to cache your DOM elements. Alternatively use for tag in tags
instead of jQuery.each tags, (tag) -> ...
:
for tag in tags
do ->
target = content.find(tag)
$(tag + "-btn").toggle ->
container.hide()
target.show()
, ->
container.show()
(the do ->
IIFE is necessary to keep each target
in scope, as @epidemian pointed out)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With