Reputation: 2683
Hey i have managed to bodge some javascript that will open a panel and close other open panels when an div is clicked. The code works but i know there is a cleaner way of doing this as if my menu had 100 elements the javascript would be huge.
How do have the same functionality but scaleable?
HTML
<div class="type" id="flip1">Button</div>
<div class="info" id="panel1"><p>Lorem ipsum.</p></div>
<div class="type" id="flip2">Button</div>
<div class="info" id="panel2"><p>Lorem ipsum.</p></div>
<div class="type" id="flip3">Button</div>
<div class="info" id="panel3"><p>Lorem ipsum.</p></div>
Javascript
$(document).ready(function(){
$("#flip1").click(function(){
$("#panel1").slideDown("slow");
$("#panel2").slideUp("slow");
$("#panel3").slideUp("slow");
});
});
$(document).ready(function(){
$("#flip2").click(function(){
$("#panel2").slideDown("slow");
$("#panel1").slideUp("slow");
$("#panel3").slideUp("slow");
});
});
$(document).ready(function(){
$("#flip3").click(function(){
$("#panel3").slideDown("slow");
$("#panel1").slideUp("slow");
$("#panel2").slideUp("slow");
});
})
Upvotes: 0
Views: 153
Reputation: 174
hide all .info on default.
$(".type").click(function(){
$(this).next().slideToggle("slow").siblings('.info').slideUp("slow");
});
Upvotes: -1
Reputation: 36662
This should do it...
$(".type").click(function(){ /* when any .type is clicked ... */
$(".info").slideUp("slow"); /* ...close all of the .info's... */
$(this).next().slideDown("slow"); /* ...open the closest (next in the DOM) .type. $(this) refers to the element that triggered the event ie. the element that was clicked */
});
Upvotes: 4
Reputation: 360
I would recommend using jquery and doing a forEach on the elements or taking it one step further and using some sort of MVC framework like Angular or Ember that provide things like components and forEach and such, so you could reuse it as a component, have a list of components, and forEach through them.
Upvotes: 0