Reputation: 753
I have several buttons with same text inside - each button opens a containing div when clicked. Problem is, that i cant make text change only on the SINGLE button clicked - when i click a button the text changes simultaneously on ALL buttons.
Does anyone know how do change the text in only the button clicked?
This is the code i have so far - the jQuery is not working correctly:
HTML
<div class="btn"> SHOW </div>
<div class="pre_hide" style="background: blue">
<h5>BOX 1</h5>
</div> <!-- END OF pre_hide -->
<br>
<div class="btn"> SHOW </div>
<div class="pre_hide" style="background: blue">
<h5>BOX 2</h5>
</div> <!-- END OF pre_hide -->
<br>
<div class="btn"> SHOW </div>
<div class="pre_hide" style="background: blue">
<h5>BOX 3</h5>
</div> <!-- END OF pre_hide -->
JQuery
$('.btn').click(function(){
if(event.target === this) { // THIS IS NOT WORKING !!
if ($(this).text() == "HIDE") {
$('.btn').text("SHOW");
$(this).next('.pre_hide').css({'display': 'none'});
}
else {
$('.btn').text("HIDE");
$(this).next('.pre_hide').css({'display': 'block'});
}
}
});
Upvotes: 0
Views: 170
Reputation: 55200
Try this.
$('.btn').click(function () {
var elm = $(this); //touch DOM once. she is too precious
if (elm.text() == "HIDE") {
elm.text("SHOW").next(".pre_hide").hide();
} else {
elm.text("HIDE").next(".pre_hide").show();
}
});
Fiddle: http://jsfiddle.net/codovations/TkTL9/1/
Upvotes: 1
Reputation: 23
$('.btn', $(this)).text('SHOW');
or
$('.btn', $(this)).text('HIDE');
Upvotes: 1
Reputation: 6720
this should work:
$('.btn').click(function(){
if ($(this).text() == "HIDE") {
$(this).text("SHOW");
$(this).next('.pre_hide').css({'display': 'none'});
}
else {
$(this).text("HIDE");
$(this).next('.pre_hide').css({'display': 'block'});
}
});
Upvotes: 5
Reputation: 4636
Try using the following:
$('.btn').click(function(){
if ($(this).text() == "HIDE") {
$('.btn').text("SHOW");
$(this).next('.pre_hide').css({'display': 'none'});
}
else {
$('.btn').text("HIDE");
$(this).next('.pre_hide').css({'display': 'block'});
}
});
Upvotes: 1
Reputation: 1219
You made the change over the $('.btn')
not $(this)
that's why you change all the buttons texts.
Try change this:
$('.btn').text("SHOW");
To:
$(this).text("SHOW");
Upvotes: 2