Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Show / Hide Divs

Tags:

html

jquery

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>
like image 454
JeffVader Avatar asked Sep 08 '26 12:09

JeffVader


1 Answers

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

like image 153
adeneo Avatar answered Sep 11 '26 05:09

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!