DEV Community

Ashok Naik
Ashok Naik

Posted on

Using CSS with Javascript to create a Read-More button

There are instances in Website-Development when you need to create a webpage in which we need to describe a product or show reviews of a product and sometimes even display a glimpse of a post.

The Read More or View More or Show More button comes handy in that situation.
This article helps you in creating such a Read More and Read Less Button.

Alt Text

We will wrap our text within a paragraph tag and create few elements within the paragraph tag which have an id attribute that will later be used by JS function and create a button which invokes the JS function.

Alt Text

Using CSS we can hide the span which contains our extra text(using display:none).

Alt Text

The readMore() function holds the entire logic to hide and display the extra text. In this function, we get the reference of useful HTML elements using DOM.
We can modify the styling of the element through Javascript. So whenever the readMore function is invoked, if the dots span element has a display property of none which means the extra text is visible, we then hide the extra text element and change the inner text of the button to Read More and change the style property of dots to inline and if the dots are visible which the extra text is not visible, we than hide the dots and display the extra text and change the inner text of the button to Read Less.

Using the following snippets you can try out this example.

Top comments (0)