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';

There is a bunch of other ways, as well.


  1. User Avatar
    Permalink to comment#

    'more otpions'

    Small typo. Great snipped though.

  2. User Avatar
    Mathias Bynens
    Permalink to comment#

    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. User Avatar
    Permalink to comment#

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

  4. User Avatar
    Permalink to comment#

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

    $("#more-less-options-button").click(function() {
          return ($("#extra-options").is(':visible') ? 'more options' : 'less options');
  5. User Avatar
    Permalink to comment#

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

    $(“#more-less-options-button”).click(function() {
    return ($(“#extra-options”).is(‘:visible’) ? ‘more options’ : ‘less options’);

  6. User Avatar
    Permalink to comment#

    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

  7. User Avatar
    Clinton Green
    Permalink to comment#

    Brilliant, exactly what I was looking for I already had the click function but was battling to add a toggle function to the expand, contract icons. Cheers

  8. User Avatar
    Permalink to comment#

    Thanks a lot. This works like cheese. So Smooth and perfect.

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.