Kali
Kali

Reputation: 17

Change button text after click

I made a "show more" button and it's working correctly, but I wish a toggle 'show more' > 'show less' > 'show more'... I tried this way but it's not working. I'm not good with jquery and javascript.

<button type="button" id="hideshow" class="btn btn-danger btn-ver-mais">SHOW MORE </button>


jQuery(document).ready(function(){
        jQuery('#hideshow').on('click', function(event) {        
             jQuery('#btn-show-more').toggle('show');
        });
    })

$(function(){
   $("#hideshow").click(function () {
      $(this).text(function(i, text){
          return text === "SHOW MORE" , "SHOW LESS" , "SHOW MORE";
      })
   });
})

Upvotes: 1

Views: 266

Answers (2)

Nikush
Nikush

Reputation: 454

Without seeing your HTML, it is hard to advise you. However, I think I have an idea of what you are trying to do.

Your HTML looks something like this for the show more button:

<div id="hideshow">Show More</div>

In order to change the text I would do something like this (fixed)

$(function() {
    $('#hideshow').click(function() {
        if ($(this).text() === 'Show More') {
            $(this).text('Show Less');
        } else {
            $(this).text('Show More');
        }
    });
});

Upvotes: 1

zer00ne
zer00ne

Reputation: 43870

Going by the code provided. The demo is using a ternary conditional:

/* declared variable: */ 
   var txt = 
/* conditional */// 'if the text of the button is SHOW MORE'...'
   $(this).text() === 'SHOW MORE'
// '...It  is now 'SHOW LESS...'
   ? 'SHOW LESS'
// ...otherwise it is 'SHOW MORE'
   : 'SHOW MORE'

Demo

$('#hideshow').on('click', function(event) {
  // 🢃 Place this INSIDE your toggle function 🢃
  var txt = $(this).text() === 'SHOW MORE' ? 'SHOW LESS' : 'SHOW MORE';
  $(this).text(txt);
  // 🢁 Place this INSIDE your toggle function 🢁
  $('#btn-show-more').toggle('show');
});
<article>
  <p>Chuck Norris has two speeds. Walk, and Kill.
    <button type="button" id="hideshow" class="btn btn-danger btn-ver-mais">SHOW MORE</button></p>
  <p id='btn-show-more' style='display:none'>
    Chuck Norris does not eat, he fights hunger When Chuck Norris finds fools' gold it automatically turns into real gold. Chuck Norris is nobody's fool, Chuck Norris once beat a wall at bloody knuckles. Chuck Norris drives an ice cream truck covered in human
    skulls.
  </p>
</article>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

Related Questions