Button that when clicked shows only content of certain class

Asked

Viewed 1,287 times

4

Hello, I’m creating a Javascript system, where I need a button to show only paragraphs with a certain class in a div with hidden content.

Example:

 <button id="btn1">Abre classe1</button>
 <div id="conteudo">
     <p class="classe1">Teste1</p>
     <p class="classe1">Teste2</p>
     <p class="classe2">Teste3</p>
 </div>

I would like when this button was clicked, the div would only press the text Teste1 and Teste2. It is possible?

Thank you.

  • What do you mean by "show only"? Will this content be hidden? or should it be shown in another element?

  • This is a div with hidden content.

  • What’s hidden, the entire div or what’s inside it? You can include that part of your CSS in the question?

2 answers

3

To show these elements with the class you want you can use like this: http://jsfiddle.net/caYtr/

$('#btn1').on('click', function(){
    $('#conteudo p.classe1').show();
});

I’m assuming you have a CSS like this:

#conteudo p {
    display: none;
}

But it would be useful to add more information to this button to create more general and not so localized code, in case there are buttons that show other classes.

Could for example join a field data-classe where it gathered the exact name of the class that this button should show.

Thus: http://jsfiddle.net/caYtr/2/

HTML

<button id="btn1" data-classe="classe1">Abre classe1</button>
<button id="btn2" data-classe="classe2">Abre classe2</button>
<div id="conteudo">
    <p class="classe1">Teste1</p>
    <p class="classe1">Teste2</p>
    <p class="classe2">Teste3</p>
</div>

Javascript/jQuery

$('button').on('click', function () {
    var classe = $(this).data('classe');
    $('#conteudo p.' + classe).show();
});

And in this case javascript no longer needs to change, regardless of having 20 more different classes.

2

If all content is hidden and is displayed only at the click of the button, you can do

Demo: Jsfiddle

Example:

CSS

/*oculta todos os parágrafos dentro da div conteúdo*/
#conteudo p {display:none;} 

jQuery

//Ao clicar no botão com id #btn1, exibe os parágrafos com .classe1
$('#btn1').click(function(){
    $('p.classe1').show('slow');
});

Browser other questions tagged

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