PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » Toggle Text

Toggle Text

Let's say you have a link to show more options which expands a list of options. It's says "more options". It's easy to toggle those options with .toggle() or .slideToggle(), but the text remains the same. To toggle the text too...

$("#more-less-options-button").click(function() {
     var txt = $("#extra-options").is(':visible') ? 'more options' : 'less options';
     $("#more-less-options-button").text(txt);
     $("#extra-options").slideToggle();
});

Subscribe to The Thread

  1. Pete says:

    'more otpions'

    Small typo. Great snipped though.

  2. Of course, it would be more useful to have the text strings in the HTML, one (the default text) as the element’s text content, and the other one as the value of a data-toggle-text attribute (or similar).

    In the above example you may wanna cache $("#extra-options") and $("#more-less-options-button") in a variable to prevent querying the DOM over and over again for the same elements.

  3. moche says:

    great tip
    if you use html entities like ↑
    use instead $(“#more-less-options-button”).html(txt).text();

  4. adardesign says:

    If using html() (instead of .text() is not an issue then you can have it like this.

    $("#more-less-options-button").click(function() {
         $("#more-less-options-button").html(function(i,h){
          return ($("#extra-options").is(':visible') ? 'more options' : 'less options');
    });
         $("#extra-options").slideToggle();
    });
  5. adardesign says:

    Sorry (no editing comments here), I meant like this:

    $(“#more-less-options-button”).click(function() {
    $(this).html(function(i,h){
    return ($(“#extra-options”).is(‘:visible’) ? ‘more options’ : ‘less options’);
    });
    $(“#extra-options”).slideToggle();
    });

  6. Jbakes says:

    So if i wanted to apply this to multiple things I want to toggle, how do I keep them separated? so if i click one element, the rest don’t follow suit

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~