Accore LTD
Accore LTD

Reputation: 287

how to trigger each class separately

Below is my code for jQuery slide on-off. Very simple code but I can't trigger each separately. When I click one, everything will be triggered simultaenously. I know it is for all same class, but I can't understand what will I do with that. I have lot of div like that.

HTML

<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>
<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>
<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>
<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>

CSS

.answerarea {
    float: left;
    width: 350px;
    margin:20px;
}
.ans {
    padding: 5px;
    background-color: #990;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    cursor:pointer;
}
.answertxt {
    background-color: #06C;
    display:none;
    color: #FFF;
    padding: 2px;
    float: left;
}
.answer {
    float: left;
}

JS

$(document).ready(function(){
        $('.ans').click(function (e) {
    e.stopPropagation();
    if($('.answertxt').hasClass('visible')) {
        $('.answertxt').stop().hide('slide', {direction: 'left'}, 500).removeClass('visible');
    } else {
        $('.answertxt').stop().show('slide', {direction: 'left'}, 500).addClass('visible');
    }
   });
});

demo http://jsfiddle.net/JSkZU/

N.B. admin/mod i am sorry for not proper subject line. actually i don't understand what subject will be fit for this issue. you can fix. thanks

Upvotes: 0

Views: 51

Answers (1)

PSL
PSL

Reputation: 123739

Try making your selector more specific, what you have will select all of them.

 $('.ans').click(function (e) {
        e.stopPropagation();
        var $this = $(this); //this represent the clicked element
        //Get to the closest/parent and select next and do a toggle and toggleclass on it
        $this.parent().next().stop().toggle('slide', {
            direction: 'left'
        }, 500).toggleClass('visible');

    });

Demo

.toggle() will toggle the current state of the element and .toggleClass will add/remove the class based on its absense/presence.

In order to collapse other ones, you can do:

$(document).ready(function () {
    $('.ans').click(function (e) {
        e.stopPropagation(); //did you mean e.preventDefault();
        var $this = $(this), $answerTxt = $this.closest('.answer').next();
        $answerTxt.add($('.answertxt.visible')).stop().toggle('slide', {
            direction: 'left'
        }, 500).toggleClass('visible');
    });
});

Demo

Upvotes: 1

Related Questions