Ali Alnoaman
Ali Alnoaman

Reputation: 17

How to change button text on click using jQuery

I have this slideToggle code. When I click the button that says "open", it changes the text to "close". It stays as "close"d even if you click it again so I want to change the text back to "open" when I click on "close" and vice versa.

  <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> 
$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
        $('#flip').html("close");
        reset ();
    });
});
</script>

<style> 
#panel,#flip
{
    padding:5px;
    text-align:center;
    background-color:#e5eecc;
    border:solid 1px #c3c3c3;
}
#panel
{
    padding:50px;
    display:none;
}
</style>
</head>
<body>

    <div id="flip">open</div>
    <div id="panel">Hello world!</div>

Upvotes: 0

Views: 1015

Answers (3)

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

try below code.

$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
        var t=$('#flip').html()==='close'?'open':'close';
        $('#flip').html(t);
        reset ();
    });
});

Better you can have a boolean to check what you are showing. like:

var showingClose=false;

$(document).ready(function(){
......
    $("#panel").slideToggle("slow");
    if(showingClose){
        $('#flip').html('open');
    }else{
        $('#flip').html('close');
    }
    showingClose = !showingClose;
.......

As pointed out by @filoxo in comment, better to use $('#flip').text() to get/set value.

Upvotes: 1

filoxo
filoxo

Reputation: 8370

You can leverage jQuery's .is() function in conjunction with the visibility selector to determine if the element is displayed or not. This is better than a boolean in my opinion and is also better for readability. Lastly, using a ternary operator can help you set the button text correctly based on said visibility.

$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
        var btnTxt = $("#panel").is(":visible") ? "close" : "open";
        $('#flip').text( btnTxt );
        reset ();
    });
});

Upvotes: 0

swift
swift

Reputation: 1108

Just toggle the css class. Check http://api.jquery.com/toggleclass/

$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").toggleClass("flip");
    });
});

css:

#panel
{
    padding:50px;
    display:none;
}
.flip
{
    padding:5px;
    text-align:center;
    background-color:#e5eecc;
    border:solid 1px #c3c3c3;
}

Upvotes: 0

Related Questions