2
votes

I'm using the following jQuery and HTML to show and hide divs when the links are clicked.

This works well if I click Brazil the div is shown correctly. However if I then click America that is also shown but Brazil isn't hidden.

How do I toggle the display so only one div is show at any one time.. ?

$(document).ready(function() {
$('.toggle').prev().data('is_visible', true);
$('.toggle').hide();
$('a.togglelink').click(function() {
$(this).data('is_visible', !$(this).data('is_visible'));
$(this).parent().next('.toggle').toggle('slow');
return false;
    });
});

<ul id="list">
<li><a href="#" class="togglelink">America</a></li>
<div class="toggle" style="display: block;"><p>America - USA - the States</p></div>

<li><a href="#" class="togglelink">Brazil</a></li>
<div class="toggle" style="display: block;"><p>Brazil - Federative Republic of Brazil</p></div>
</ul>
</div>
2

2 Answers

8
votes

Start by fixing the markup, a DIV can not be a direct child of an UL.

<ul id="list">
    <li>
        <a href="#" class="togglelink">America</a>
        <div class="toggle" style="display: block;">
            <p>America - USA - the States</p>
        </div>
    </li>
    <li>
        <a href="#" class="togglelink">Brazil</a>
        <div class="toggle" style="display: block;">
            <p>Brazil - Federative Republic of Brazil</p>
        </div>
    </li>
</ul>

Then do:

$(document).ready(function () {
    $('.toggle').hide();
    $('a.togglelink').on('click', function (e) {
        e.preventDefault();
        var elem = $(this).next('.toggle')
        $('.toggle').not(elem).hide('slow');
        elem.toggle('slow');
    });
});

FIDDLE

1
votes

I think you're doing things too complicated with your data binding. Can you please check my example DEMO

This do the job:

$(document).ready(function() {   
$('.toggle').hide();
$('a.togglelink').click(function() {
    $('.toggle').hide();
    $(this).parent().next('.toggle').toggle('slow');
    return false;
});

});