How to show only the selected div

Asked

Viewed 639 times

1

I have a list with 3 elements and 3 Divs.

<ul>
    <li>Todos</li>
    <li>elemento 1</li>
    <li>elemento 2</li>
    <li>elemento 3</li>
</ul>

<div id="1">elemento 1</div>
<div id="2">elemento 2</div>
<div id="3">elemento 3</div>

What I’m trying to do is click on an element in the list and show the corresponding div and hide the other Ivs. Can someone show me some ways to do this with jquery?

1 answer

3


See if this fits you:

$(function() {
    $('ul#items li').click(function(){
        var item = $('.elem[data-item="' + $(this).attr('data-item') + '"]');
        if($(this).attr('data-item') == 'all') {
            $('div.elem').show();
            return;
        }
        item.show();                                     
        $('div.elem[data-item!="'+item.attr('data-item')+'"]').hide();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="items">
    <li data-item="1">elemento 1</li>
    <li data-item="2">elemento 2</li>
    <li data-item="3">elemento 3</li>
    <li data-item="all">Todos</li>
</ul>

<div data-item="1" class="elem">elemento 1</div>
<div data-item="2" class="elem">elemento 2</div>
<div data-item="3" class="elem">elemento 3</div>

Elements are associated by the attribute data-item, namely, the li where the value of the attribute data-item is 3 will show the div with data-item 3 and hide the others. The element with data-item equal to all will show all Divs again.

If you want the others to be hidden by default just add one display: none in css.

  • Thanks André! Served yes. I modified the code as I would show all the elements?

  • 1

    @ewertonorg you say show all the Divs again? Type reset the filter?

  • Exactly, when I click on the 'all' option and shows all the Divs I had before.

  • @ewertonorg edited my answer to add this feature. Take a look there.

  • vlw André, +1 for you! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.