Change the text of a link via CSS

A typical example of a link that changes it’s text is when you would like to create section on your website and need a link that says Collapse when the section is open and says Expand when the section is closed.

Create a simple closable section

First, let’s create a simple link that will open and close our section with the help of a little JavaScript. The HTML part:

<a class="toggle-button" href="#">Collapse/Expand</a>

<section class="expandable">
    This is an expandable section.
</section>

The JavaScript part:

$(function() {
    $('.toggle-button').on('click', function() {
    	$('.expandable').toggle();
    });
});

Clicking the link can open and close the section. So our program is working fine, but we could improve it a little bit by changing the text of the link depending on the status of our section.

Add text changing functionality via CSS

Let’s add a wrapper around our HTML elements and change the classnames:

<div class="expandable-container">
    <a class="toggle-button" href="#" data-collapsed="Expand" data-expanded="Collapse"></a>
    <section class="expandable-content">
        This is an expandable section.
    </section>
</div>

Our JavaScript will also need to be changed, because we would like to add the expanded class to the parent of the content that we would like to show/hide.

$(function() {
    $('.toggle-button').on('click', function() {
        $(this).parent().toggleClass('expanded');
    });
});

Now comes the most important part. As you can see in our HTML we provided the Expand and Collapse texts is data attributes. We will use CSS to read these attributes and set them as the link’s text.

.expandable-container .toggle-button:after {
    content: attr(data-collapsed);
}
.expandable-container.expanded .toggle-button:after {
    content: attr(data-expanded);
}

.expandable-container .expandable-content {
    display: none;
}

.expandable-container.expanded .expandable-content {
    display: block;
}

The text of the link is set using the :after psedo attribute. The content inserted this way should behave as it would be a normal child of the element, but some browsers have issues interpreting them. In an other article I discussed a possible problem that could come up on certain browsers: Link with pseudo attribute is not clickable on mobile browser (Samsung Galaxy S3)