<button
data-component="toggler"
data-toggler-toggleable="toggleable-a"
>
Show/Hide A
</button>
<button
data-component="toggler"
data-toggler-toggleable="toggleable-b"
>
Show/Hide B
</button>
<div data-toggler-target="toggleable-a">
<p>A: I can be shown or hidden!</p>
</div>
<div data-toggler-target="toggleable-b">
<p>B: I can be shown or hidden!</p>
</div>
div {
display: none;
}
.is-active {
display: block;
}
View Compiled
# component.coffee
class Component
# @param {String} name
# @param {Array<String>} targets
# @param {Function} functionality
# @return {void}
constructor: (name, targets = [], functionality) ->
selector = "[data-component='#{name}']"
$(selector).each ->
config =
element: this
selector: selector
# Register target selectors.
targets.forEach (t) ->
targetAttr = "data-#{name}-#{t}"
targetName = $(config.element).attr(targetAttr)
config[t] = "[data-#{name}-target='#{targetName}']"
# Run passed function with config object.
functionality(config)
# toggler.coffee
new Component 'toggler', ['toggleable'], (c) ->
$(c.element).on 'click', () ->
$(c.toggleable).toggleClass('is-active')
View Compiled
This Pen doesn't use any external CSS resources.