sachq
sachq

Reputation: 672

Show/Hide using toggle jQuery

jQuery Script
This code works, But Is it possible to add 'options' inside the slideToggle method so that I toggle '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);
    });
});

http://jsfiddle.net/sachq/mt3duxzk/1/

Upvotes: 3

Views: 863

Answers (3)

CodeGodie
CodeGodie

Reputation: 12142

You can go ahead and give this a try. You may also change the "complete" option to "start" if you want the callback to fire as soon as you click the button.

DEMO: HERE'S A 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);
            }
        });
    });

Upvotes: 2

dfsq
dfsq

Reputation: 193301

I can suggest better approach. The idea is that you should not hardcode your button texts into javascript code. It makes code very obtrusive and tightly coupled, because if you decide to change the text from "Show" to "Show more" you will have to modify javascript code as well. Instead you can have both labels in place but show only 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 disagrees with me. But it is easy to see that the benefits of slightly increased amount of code are bigger then it might look at first. Approach described above is much more flexible then comparing text strings. Not to mention it also allows advanced styling of the buttons with images and other elements which could be problematic with hardcoded strings.

Demo: http://jsfiddle.net/mt3duxzk/3/

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59292

You can't do that, but you can simplify things to ternary operator.

button.text(function(_, txt){
   return txt == "Show" ? "Hide" : "Show"
}).next().slideToggle(300);

Upvotes: 0

Related Questions