Reputation: 2584
How can I toggle the button text once the content is visible? How can I hide the content if I click on the button again?
Here is what I mean: JSFiddle
I want to change the button text from View content to Hide content and the icon class from fa-arrow-circle-down
to fa-arrow-circle-up
$('.js-show-content').bind('click', function(){
$(".content").slideDown(200);
return false;
});
Upvotes: 2
Views: 773
Reputation: 13666
You can do it like this:
$('.js-show-content').bind('click', function(){
$('.content').slideToggle(200);
$(this).find('i').toggleClass('fa-arrow-circle-down fa-arrow-circle-up');
$(this).find('span').html(function(i, text){
return text === 'Hide content' ? 'View content' : 'Hide content';
});
return false;
});
Additionally you will have to modify the HTML slightly by wrapping the button text in a span
so that when you modify the text you do not remove the i
element:
<a class="js-show-content btn btn-default" href="#" role="button"><i class="fa fa-arrow-circle-down fa-md"></i> <span>View content</span></a>
As others have stated, you can use jQuery's slideToggle to show/hide the .content
div using a single line of code. The next part uses toggleClass to switch between the up
and down
arrow icons on the i
element. Finally, we are swapping out the text with a simplified if/else statement which checks the current text of the button, if it matches then the text is changed, if it doesn't match then it switches back to the initial text.
Upvotes: 5
Reputation: 2114
Here is one simple way to do it:
$('.js-show-content').bind('click', function () {
var btn = $(this);
$(".content").slideToggle(200, function () {
// Toggle button content
if (btn.find('.fa-arrow-circle-down').length)
btn.html('<i class="fa fa-arrow-circle-up fa-md"></i> Hide content');
else
btn.html('<i class="fa fa-arrow-circle-down fa-md"></i> View content');
});
return false;
});
JSFiddle: http://jsfiddle.net/0gctxtmv/4/
Upvotes: 0
Reputation: 2254
You can achieve the effect using jquery slide toggle.
$( ".js-show-content" ).click(function() {
$( ".content" ).slideToggle( "slow" );
});
Upvotes: 0
Reputation: 10305
jQuery has a built-in function called .slideToggle()
which you can read about here: http://api.jquery.com/slidetoggle/
Other than that, you will just have to use conditionals to change the CSS properties, although I would suggest, if you are using your own CSS to make a default CSS property the arrow down, and when you click add a class that overrides that arrow. Click again- remove the override CSS class and restore the button back to default
Upvotes: 0
Reputation: 23
https://jsfiddle.net/brunodd/0gctxtmv/
I don't know about your button text, but now it toggles back up again when you reclick
$('.js-show-content').bind('click', function(){
$(".content").slideToggle(200);
return false;
});
Upvotes: 0