I have a couple links and divs I would like to have the same functionality on. Basically, you click on a link/button/anything-chosen-as-the-trigger and the corresponding space slides open.
The markup looks like…
<!-- some code -->
<li><a href="#" id="first">First</a></li>
<li><a href="#" id="second">Second</a></li>
<li><a href="#" id="third">Third</a></li>
<div id="f_i_r_s_t"></div>
<div id="s_e_c_o_n_d"></div>
<div id="t_h_i_r_d"></div>
So far, I have tried to refactor
// script.js.coffee
$(document).ready ->
$('#first').click ->
$('#f_i_r_s_t').slideToggle()
// script.js.coffee
$(document).ready ->
$('#second').click ->
$('#s_e_c_o_n_d').slideToggle()
// script.js.coffee
$(document).ready ->
$('#third').click ->
$('#t_h_i_r_d').slideToggle()
which works, to
// refactored_script.js.coffee
hideables = {
'#first': '#f_i_r_s_t',
'#second': '#s_e_c_o_n_d',
'#third': '#t_h_i_r_d'
}
for content_space, link_trigger in hideables
$(content_space).hide()
$(link_trigger).click ->
$(content_space).slideFadeToggle()
but the refactored script does not work. Any ideas?
Do something like this
Adding underscores to your ID’s is just making your problem harder and less dynamic; sure it can be done. You’d just have to take the ID attr and insert a underscore between each character but … is all I have to really say about that.