I need to know how implement a toggle button

This question already has an answer here:

I have posted a question on this forum and a moderator asked to create a question and link to the original post.

This is the post. toggle show/hide div with button?

The question is regarding the solution provided by NAVEED answered Dec 24 '10 at 19:50.

I want know how can I use only the word "open" in the button when the div is closed and "close" when the div is open? I mean, switching the words open and close on the button.

Thank you.

Answers 1

  • Using the following HTML Naveed used.

    HTML

    <div id='content'>Hello World</div>
    <input type='button' id='hideshow' value='hide/show'>
    

    You can then use the following JS to both toggle a show/hide class on your button and change the text.

    JS

        var btn = $('#hideshow')
        var content = $('#content')
    
        btn.click( function() ) {
             if (content.hasClass("show"){
                 content.removeClass('show');
                 btn.text('open');
             } else{
                 content.addClass('show');
                 btn.text('close');
             }
        });
    

    CSS

    #content{
      display: none;
    }
    #content.show{
      display: block;
    }
    

Related Articles