jQuery Text Toggle, But Wildcard?

Here is the text toggle I have right now:

abutton.text(text == "Read More" ? "Read Less" : "Read More");

That works fine, but some of the buttons that will fall under this function will say “Learn More” instead of “Read More”, so I was trying to figure out a way to have the jquery only change the word instead of updating the phrase.

So, if “More” is there, change that to “Less”, and back and forth.

One-line way to do this?

Cheers!
Ryan

Right now my multiline solution is:

if (text.toLowerCase().indexOf("more") >= 0) {
                    abutton.text(text.replace("More","Less"));
                } else{
                     abutton.text(text.replace("Less","More"));
                }

If something smoother let me know.

Normally you wouldn’t parse and replace text like this in your JS – that will get messy pretty quickly, especially if you add multi language support at some point. You might handle this with a class though:

.toggle-content .read-less {
  display: none;
}

.toggle-content.active .read-more {
  display: none;
}

.toggle-content.active .read-less {
  display: unset;
}
<a href="#" class="toggle-content">
  <span class="read-more">Read more</span>
  <span class="read-less">Read less</span>
</a>
$('.toggle-content').click(function (event) {
  event.preventDefault()
  $(this).toggleClass('active')
})

This way, all content can be edited in the HTML without requiring any adjustments to the JS.

1 Like

That is so much better. Thanks!

1 Like

Ahh,

Actually, I forgot why I was using Javascript. This is a great solution, if the button could be edited (the code), but I am writing a script that converts the WPBakery template buttons for Wordpress. So you can only add one amount of “text” into the button with WPBakery. Now, you could do a text block instead and copy/paste the typical button code and then edit it manually. But plugin and theme updates might present somewhat of an issue.

Actually!

WPBakery does allow for html to be used in the “text” field, so this should work.

Boom!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.