Reputation: 1296
Ok well I need some help because I am plain stuck. I am trying to make a simple drop down type menu which will be used for a different purpose then a navigation menu. But anyway I can get it to work perfectly, I just need some help simplyfing the code. Here is the html:
<div class="big">
<a href="#" id="atog1">Hello</a>
<a href="#" id="atog2">Hello</a>
<a href="#" >Hello</a>
<a href="#">Hello</a>
<br clear="all">
<div id="drop" class="atog1">This is a toggled div1!</div>
<div id="drop" class="atog2">This is a toggled div2!</div>
</div>
Here is the Jquery initial code that works beautifully but I am going to need to have up to 20 different a and divs to show and I do not want all that code. So I am trying to put it in a clean simple short snippet of code:
//Make the toggled div
$('#atog1').show();
$('div.atog1').hide();
$('#atog1').click(function(){
$('div.atog2').hide();
$('div.atog1').slideToggle();
});
//Make the toggled div2
$('div.atog2').hide();
$('#atog2').click(function(){
$('div.atog1').hide();
$('div.atog2').slideToggle();
});
And here is where I got stuck, This is what is supposed to be a shorter version of the above, but when I click on the first a it opens div and when I click on the second a it hides first div but then if I click on the first a again it does not hide div:
$('div[class^=atog]').hide();
$('a').click(function(){
var tid = $(this).attr('id');
$('div#drop[class!='+tid+']').hide();
$('div#drop[class='+tid+']').slideToggle();
});
I know there should be a really simple solution, but I can just not see it. Thanks to anyone in advance and here is my jsfiddle if that is more helpful! http://jsfiddle.net/liveandream/stGF9/
Upvotes: 0
Views: 394
Reputation: 78690
You can't have multiple elements with the same id
.
You should use classes when they need to be shared. Here is one example of how you could change it.
$('div.drop').hide();
$('a').click(function(){
var tid = $(this).attr('id');
var el = $('div.drop.'+tid);
$('div.drop').not(el).hide();
el.slideToggle();
});
Upvotes: 1