João Pedro
João Pedro

Reputation: 960

show and hide some span text

I just started programming and learning Jquery, I'm trying to build a simple show/hide text button, and I actually almost made it succesfully, but the problem is I have two buttons and two texts to show/hide, but when I click either of the buttons both texts show/hide. here's my code:

HTML:

<div class="mestre">
    <h2>Title</h2>
    <p>some text</p> 
 <h4>Saiba mais</h4><--the button -->
   <span class="saibamais">hidden text</span></div>
<div class="mestre">
    <h2>Title</h2>
    <p>some text</p> 
 <h4>Saiba mais</h4><--the button -->
   <span class="saibamais">hidden text</span></div>

JS

 var saibamaisBtn = $('#conteudo div.mestre h4');
    saibamais = $('#conteudo div.mestre span.saibamais');

       $(function(){ 
saibamais.css('display', 'none');
  });

 saibamaisBtn.hover(function(){
   var $this = $(this);
         $this.css('text-decoration', 'none');


},  function(){
    $(this).css('text-decoration', 'underline');

});

   saibamaisBtn.click(
    function() {
        saibamaisBtn.next('span').slideToggle('fast')
            }

            );

Upvotes: 1

Views: 2059

Answers (3)

user1056272
user1056272

Reputation:

saibamaisBtn.click(
    function() {
        $(this).closest('span.saibamais').slideToggle('fast');
    });

or

saibamaisBtn.on('click', 
    function() {
        $(this).next('span.saibamais').slideToggle('fast');
    });​

DEMO

Upvotes: 3

Jay Blanchard
Jay Blanchard

Reputation: 34416

Because saibamaisBtn represents the group of buttons you are getting the action on all of the span elements. Normally you would write it like this -

$('#conteudo div.mestre h4').click(function() {
    $(this).next('span').slideToggle('fast');
});

This will isolate the button that was clicked and focus on the span available in next().

Upvotes: 0

chris
chris

Reputation: 37450

You are doing everything based on a class, which occurs multiple times in your document.

You can replace the class with an ID, or try something like this so that only one span is affected.

Upvotes: 0

Related Questions