Daniel Williams
Daniel Williams

Reputation: 2317

Changing link text on click using CSS

My code is running a bit funny. If you click the link it should go from show more to show less and then when clicked again should go to show more however the behavior is not as expected.

#theLink.collapsed:before
{
    content:'Show less' ;
}
#theLink:before
{
    content:'Show more' ;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<a data-toggle="collapse" href="#intro" aria-expanded="false" aria-controls="intro" id="theLink"></a>

<div id="intro" class="collapse"> 
  Here comes the text...
</div>

Upvotes: 0

Views: 43

Answers (1)

fubar
fubar

Reputation: 17378

You just had your more and less text the wrong way around. The show more text needed to be shown when the link had the collapsed class.

I also initialised the link to have the collapsed class by default.

#theLink.collapsed:before
{
    content:'Show more' ;
}
#theLink:before
{
    content:'Show less' ;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<a class="collapsed" data-toggle="collapse" href="#intro" aria-expanded="false" aria-controls="intro" id="theLink"></a>

<div id="intro" class="collapse"> 
  Here comes the text...
</div>

Upvotes: 1

Related Questions