Reputation: 7688
I have this html structure:
<div id="home">
<div class="section_header">
<h1 class="left" data-target="newest"><?=lang('home_newest');?></h1>
...
</div>
<div id="newest">
...
</div>
<div class="section_header">
<h1 class="left" data-target="best"><?=lang('home_newest');?></h1>
...
</div>
<div id="best">
...
</div>
</div>
What I am trying to do is a toggle/show&hide function to work on click .section_header > h1 to show the div with the id defined in data-target inside h1 tag and hide the others, but always having one open and the #newest open by default on page load.
I have tried:
$('.section_header h1').click(function(){
var selected = $(this).data('target');
//$('#'+selected).hide().filter('#'+selected).show();
$('#home > #'+selected).hide();
}).first().click();
The commented line doesn't work, but the .hide only it does.
I found this: http://www.learningjquery.com/2007/02/more-showing-more-hiding and thought it could work but I didn't succeed to tell it which div to close and show
Edit: There is one more thing, how can it be done that when clicked on the visible div to close it and open the next one?
Upvotes: 1
Views: 1368
Reputation: 865
try this:
html:
<div id="home">
<div class="section_header">
<h1 class="left" data-target="newest">h1<?=lang('home_newest');?></h1>
</div>
<div id="newest">
...
</div>
<div class="section_header">
<h1 class="left" data-target="best">h2<?=lang('home_newest');?></h1>
</div>
<div id="best">
...
</div>
</div>
css
#home div { display: none;}
#home div.section_header { display:block;}
js
$(document).ready(function() {
$('.section_header > h1').click(function() {
showOnlySingleHeader.call(this);
});
showOnlySingleHeader.call($('.section_header > h1[data-target="newest"]'));
});
function showOnlySingleHeader() {
$('#' + $(this).data('target')).toggle();
$('.section_header > h1').not(this).each(function() {
$('#' + $(this).data('target')).hide();
});
}
Here's a JSFiddle
EDIT It should now comply to your requirements
Upvotes: 1
Reputation: 8454
See this Fiddle for a working version of your code.
$('.section_header h1').on('click', function(){
$('#home > div:not(.section_header)').hide();
$('#' + $(this).data('target')).show();
}).first().click();
Upvotes: 2