Frank Capone
Frank Capone

Reputation: 21

jQuery Toggling Button Visibility On Click

I'm looking to 'cycle' between two buttons on a click event. It's trivial to do but I wonder if there is a more concise way to achieve it than what I have below.

$('button#start').click( function() {

    $(this).addClass('hide');
    $('button#stop').removeClass('hide');

});

$('button#stop').click( function() {

    $(this).addClass('hide');
    $('button#start').removeClass('hide');

});

Upvotes: 2

Views: 6064

Answers (3)

Jared Farrish
Jared Farrish

Reputation: 49208

It bugs me I'm not caching that $(this), but it's not necessary and won't give any realized performance gains in my opinion. However, I imagine this is about as short as it's going to get:

$('#start, #stop').click(function(){
    $(this).hide();
    $(this).siblings('button').show();
});

http://jsfiddle.net/userdude/S4d6j/1/

So, it depends on your DOM structure and where the elements are. The alternative could be to just use this.id to determine which was clicked and then toggle values accordingly:

$('#start, #stop').click(function(){
    var buttons = {start: 'stop', stop: 'start'};

    $(this).hide();
    $('#' + buttons[this.id]).show();
});

http://jsfiddle.net/userdude/S4d6j/3/

EDIT: Made it even more consise with $(this).hide().

No trickiness, Nixonian ternaries, or duplication in the handlers. Just nice and simple.

Upvotes: 1

dansch
dansch

Reputation: 6267

$('button').click(function(e){
    $(  
         $(this).addClass('hide').attr('id') == 'start' 
              ? '#stop' 
              : '#start'
    ).removeClass('hide');
});

this one will hide the button while it gets the id, it will select the stop id if the current id attribute is start and vice versa. it uses hide and show but you could substitute in addClass('hide') etc

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

Another simple demo http://jsfiddle.net/S4d6j/

Good read: visible selector: http://api.jquery.com/visible-selector/

You can use .is(":visible") to check which one is visible and hide the other, and we can chain both buttons.

Hope it helps

code

$('#start,#stop').click(function() {

    if ((this.value === "start") && $(this).is(":visible")) {        
        $("#stop").show();
    } else if ((this.value === "stop") && $(this).is(":visible")) {
        $("#start").show();
    }

    $(this).hide();

});​

Upvotes: 2

Related Questions