How to change the text of a link after clicked?

Asked

Viewed 1,464 times

7

How do I do in HTML (or CSS if you have how) the text of a link where it is written "show more" change to "show less" and vice versa after clicked?

  • No javascript or jQuery?

3 answers

4


Solution with javascript, you can do so:

const link = document.getElementById('my_link');
var less = false;

link.addEventListener('click', function(){
  this.innerHTML = (less = !less) ? 'Mostrar Menos' : 'Mostrar Mais';
});
<a id="my_link" href="#">Mostrar Mais</a>

  • Legal @Miguel! this.innerHTML = 'Mostrar menos' == this.innerHTML ? 'Mostrar mais' : 'Mostrar menos'; works also and would dispense the if , to var less and the body would have a line :)

  • It’s true @Lucascosta, edited now. Thank you

  • It worked, vlw! :-)

  • You’re welcome @Marcio.Sx, thank goodness (:

3

With jQuery you can exchange text at the event click of the link:

$("a").click(function(){
  var texto = $(this).text();
   $(this).text(texto == "Mostrar mais" ? "Mostrar menos" : "Mostrar mais");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Mostrar mais</a>

3

window.onload = function() {
  var el = document.getElementsByClassName('texto')[0];
  var btn = document.getElementById("read-more");

  btn.onclick = function() {
    if (btn.innerHTML == 'Mostrar Mais') {
      el.style.height = 'auto';
      btn.innerHTML = 'Mostrar Menos';

    } else {
      el.style.height = '40px';
      btn.innerHTML = 'Mostrar Mais';
    }
  }

}
.texto {
  overflow: hidden;
  height: 40px;
}
<div class="texto">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero nemo veniam tempora saepe obcaecati quas enim officiis ad voluptate provident nisi dicta impedit, dolorem ipsam, reprehenderit pariatur laborum, odit temporibus! Lorem ipsum dolor sit amet,
  consectetur adipisicing elit. Odio atque eaque qui dicta ducimus, laboriosam in, laudantium maiores, animi ut error ullam soluta expedita illo tempora. Dolorem, aliquam quis nostrum.
</div>
<a href="#" id="read-more">Mostrar Mais</a>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.