Reputation: 585
I am using the following code to show/hide a div when an anchor is clicked.
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
So, when the 'show_hide' div is clicked, 'slidingDiv' shows. But, how can I change the text of the 'show_hide' div once it is clicked. E.g. I want 'show_hide' to read 'Toggle Open', how can i change it once it is clicked to 'Toggle Close' ?
Thanks!
Upvotes: 3
Views: 906
Reputation: 8199
You can make it this way :
JS :
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
$(this).toggleClass('open');
});
HTML :
<a href="#" class="show_hide">
<span class="textopen">Toggle Open</span>
<span class="textclose">Toggle Close</span>
</a>
CSS :
.textclose {display: none;}
.show_hide.open .textopen {display: none;}
.show_hide.open .textclose {display: inline;}
I personaly prefer to keep the text in the html rather than JS for maintenance purpose for example. Your javascript also keeps clean and simple.
Upvotes: 1
Reputation: 318352
Create a toggle functionality for the text as well using the text()
method and a callback
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
$(this).text(function(_, txt) {
return txt === 'Toggle Open' ? 'Toggle Close' : 'Toggle Open';
});
});
To use the text from the anchor, you'd store it in data()
, like this
$('.show_hide').each(function() {
$(this).data('default_text', $(this).text())
}).click(function(){
$(".slidingDiv").slideToggle();
var text = $(this).data('default_text');
$(this).text(function(_, txt) {
return txt === text ? 'Toggle Close' : text;
});
});
And you could define the alternate text in the HTML as well, using a data attribute
<a href="#" class="show_hide" data-close="Search Close">Search</a>
and do
$('.show_hide').each(function() {
$(this).data('default_text', $(this).text())
}).click(function(){
$(".slidingDiv").slideToggle();
var text = $(this).data('default_text');
$(this).text(function(_, txt) {
return txt === text ? $(this).data('close') : text;
});
});
Upvotes: 5