Show / hide with toggle jQuery
jQuery Script
This code works, but is it possible to add "parameters" inside the slideToggle method so that I toggle the Show / Hide text?
$(function() {
var container = $('div.container p'),
button = $('div#click');
container.hide();
button.on('click', function() {
if (button.text() == 'Show') {
button.text('Hide');
} else {
button.text('Show');
}
$(this).next().slideToggle(300);
});
});
source to share
You can go and try it. You can also change the "full" option to "start" if you want the callback to fire as soon as you press the button.
DEMO: HERE FIDDLE
var container = $('div.container p');
var button = $('div#click');
container.hide();
button.on('click', function(){
container.slideToggle({
duration: 200,
complete: function(){
var txt = (button.text() === 'Show') ? "Hide" : "Show";
button.text(txt);
}
});
});
source to share
I can suggest a better approach. The idea is that you shouldn't hard-code the button texts into javascript code. This makes the code very intrusive and tightly coupled, because if you decide to change the text from Show to Show More, you also have to change the JavaScript code. Instead, you can have both labels in place, but only show one at a time:
<div id="click"><span class="show">Show</span><span class="hide">Hide</span></div>
JavaScript:
button.on('click', function () {
button.toggleClass('hide');
$(this).next().slideToggle(300);
});
and CSS:
div#click > span {
display: none;
}
div#click .show {
display: inline-block;
}
div#click.hide .hide {
display: inline-block;
}
div#click.hide .show {
display: none;
}
UPD. Apparently, someone does not agree with me. But it's easy to see that the benefits of a slightly increased amount of code are more than meets the eye. The approach described above is much more flexible than comparing text strings. Not to mention, it also allows you to promote the style of buttons with images and other elements that can be problematic with hard-coded strings.
Demo: http://jsfiddle.net/mt3duxzk/3/
source to share