How to change the text of a link after it has been clicked?

7

How do I get the text of a link where to be written "show more" change to "show less" and vice versa when clicked? >     

asked by anonymous 28.12.2016 / 17:39

3 answers

4

Solution with javascript, you can do this:

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>
    
28.12.2016 / 17:44
3

With jQuery you can change the text in the click event 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><ahref="#">Mostrar mais</a>
    
28.12.2016 / 17:45
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>
    
28.12.2016 / 17:51