show more/Less text with just HTML and JavaScript
I am needing to create a show more/less text function, but with just JavaScript and HTML.. I can’t use any additional libraries such as jQuery and it can’t be done with CSS. The sample code I have added displays the ‘more’ text, but not the ‘less’. If someone could point me in the right direction, it would be much appreciated. I’ve spent the majority of the day frying my brain over this, as its clearly not the modern way to do it, however, my HTML is:
Lorem ipsum dolor sit amet See More
Here is some more text
The answers will differ pending more detail of your requirements. If your text is going to be static and not repeated elsewhere. You could toggle the display like in @akhikhl answer. This is probably requires the least amount of code?
12 Answers 12
My answer is similar but different, there are a few ways to achieve toggling effect. I guess it depends on your circumstance. This may not be the best way for you in the end.
The missing piece you’ve been looking for is to create an if statement. This allows for you to toggle your text.
var status = "less"; function toggleText() < var text="Here is some text that I want added to the HTML file"; if (status == "less") < document.getElementById("textArea").innerHTML=text; document.getElementById("toggleButton").innerText = "See Less"; status = "more"; >else if (status == "more") < document.getElementById("textArea").innerHTML = ""; document.getElementById("toggleButton").innerText = "See More"; status = "less" >>
With some HTML changes, you can absolutely achieve this with CSS:
#textarea < display: none; /* hidden by default */ >#textarea:target < display: block; /* shown when a link targeting this id is clicked */ >#textarea + ul.controls < list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */ >/* hiding the hide link when the #textarea is not targeted, hiding the show link when it is selected: */ #textarea + ul.controls .hide, #textarea:target + ul.controls .show < display: none; >/* Showing the hide link when the #textarea is targeted, showing the show link when it's not: */ #textarea:target + ul.controls .hide, #textarea + ul.controls .show
Or, you could use a label and an input of type=»checkbox» :
Lorem ipsum dolor sit amet All that delicious text is in here!
Here is some more text
#textarea < /* hide by default: */ display: none; >/* when the checkbox is checked, show the neighbouring #textarea element: */ #textAreaToggle:checked + #textarea < display: block; >/* position the checkbox off-screen: */ input[type="checkbox"] < position: absolute; left: -1000px; >/* Aesthetics only, adjust to taste: */ label < display: block; >/* when the checkbox is unchecked (its default state) show the text 'Show ' in the label element: */ #textAreaToggle + #textarea + label::before < content: 'Show '; >/* when the checkbox is checked 'Hide ' in the label element; the general-sibling combinator '~' is required for a bug in Chrome: */ #textAreaToggle:checked ~ #textarea + label::before
Great CSS-only solution, except wouldn’t really work if there are n distinct textarea elements on a page that need to toggled between hide and show
This almost worked for me. I had to change the last instruction to targetEle.style.height = (targetEle.style.height == limitedHeight) ? ‘initial’ : limitedHeight;
This is my pure HTML & Javascript solution:
var setHeight = function (element, height) < if (!element) else < var elementHeight = parseInt(window.getComputedStyle(element, null).height, 10), toggleButton = document.createElement('a'), text = document.createTextNode('. Show more'), parent = element.parentNode; toggleButton.src = '#'; toggleButton.className = 'show-more'; toggleButton.style.float = 'right'; toggleButton.style.paddingRight = '15px'; toggleButton.appendChild(text); parent.insertBefore(toggleButton, element.nextSibling); element.setAttribute('data-fullheight', elementHeight); element.style.height = height; return toggleButton; >> var toggleHeight = function (element, height) < if (!element) < return false; >else < var full = element.getAttribute('data-fullheight'), currentElementHeight = parseInt(element.style.height, 10); element.style.height = full == currentElementHeight ? height : full + 'px'; >> var toggleText = function (element) < if (!element) < return false; >else < var text = element.firstChild.nodeValue; element.firstChild.nodeValue = text == '. Show more' ? '. Show less' : '. Show more'; >> var applyToggle = function(elementHeight) < 'use strict'; return function()< toggleHeight(this.previousElementSibling, elementHeight); toggleText(this); >> var modifyDomElements = function(className, elementHeight) < var elements = document.getElementsByClassName(className); var toggleButtonsArray = []; for (var index = 0, arrayLength = elements.length; index < arrayLength; index++) < var currentElement = elements[index]; var toggleButton = setHeight(currentElement, elementHeight); toggleButtonsArray.push(toggleButton); >for (var index=0, arrayLength=toggleButtonsArray.length; index >
You can then call modifyDomElements function to apply text shortening on all the elements that have shorten-text class name. For that you would need to specify the class name and the height that you would want your elements to be shortened to:
modifyDomElements('shorten-text','50px');
Lastly, in your your html, just set the class name on the element you would want your text to get shorten:
I hope this helps you. Here is the functionality:
- When text characters is less than or equal to 12. Then it displays the whole text and also does not display the more/less button
- When text characters is more than 12. Displays only 12 characters of the text and also a More button which when pressed, shows the whole text.
- When the More button is pressed the button changes to Less
Read more string manipulation in w3schools: String Manipulation or Mozila: String Manipulation
var startStatus = "less"; function toggleText() < var text = "Here is the text that I want to play around with"; if (text.length >12) < if (startStatus == "less") < document.getElementById("textArea").innerHTML = `$. `; document.getElementById("more|less").innerText = "More"; startStatus = "more"; > else if (startStatus == "more") < document.getElementById("textArea").innerHTML = text; document.getElementById("more|less").innerText = "Less"; startStatus = "less"; >> else < document.getElementById("textArea").innerHTML = text; >> toggleText();
This should resolve your problem:
function toggleSeeMore() < if(document.getElementById("textarea").style.display == 'none') < document.getElementById("textarea").style.display = 'block'; document.getElementById("seeMore").innerHTML = 'See less'; >else < document.getElementById("textarea").style.display = 'none'; document.getElementById("seeMore").innerHTML = 'See more'; >>
Hope this Code you are looking for HTML:
#@item.Title
Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text
var showChar = 100; var ellipsestext = "[. ]"; $('.showmore').each(function () < $(this).find('.shorten_txt p').addClass('more_p').hide(); $(this).find('.shorten_txt p:first').removeClass('more_p').show(); $(this).find('.shorten_txt ul').addClass('more_p').hide(); //you can do this above with every other element var teaser = $(this).find('.shorten_txt p:first').html(); var con_length = parseInt(teaser.length); var c = teaser.substr(0, showChar); var h = teaser.substr(showChar, con_length - showChar); var html = '' + c + '' + ellipsestext + '' + h + ''; if (con_length > showChar) < $(this).find(".shorten_txt p:first").html(html); $(this).find(".shorten_txt p:first span.morecontent_txt").toggle(); >>); $(".showmore").click(function () < if ($(this).hasClass("less")) < $(this).removeClass("less"); >else < $(this).addClass("less"); >$(this).find('.shorten_txt p:first span.moreelipses').toggle(); $(this).find('.shorten_txt p:first span.morecontent_txt').toggle(); $(this).find('.shorten_txt .more_p').toggle(); return false; >);
Show More.
if more div use like this change only 1 to 2
I’m not an expert, but I did a lot of looking to implement this for myself. I found something different, but modified it to accomplish this. It’s really quite simple:
The function takes two arguments, a div containing only the words «show more» [or whatever] and a div containing the originally hidden text and the words «show less.» The function displays the one div and hides the other.
NOTE: If more than one show/hide on page, assign different ids to divs Colors can be changed
Here is text that is originally displayed
show more
more text
function showFunction(diva, divb)
You can also use details HTML tag which does the work for you.
Epcot Center
Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.
Here is another way to do it.
.url-container < white-space: nowrap; overflow: hidden; text-overflow: ellipsis; >.show-more < display: none; >.show-less https://www.example.com/very/long/url/that/you/want/to/show/hide
Try this approach, more styled:
document.querySelector(".expand").addEventListener("click", () => < document.querySelector(".container").classList.add("opened"); document.querySelector(".show-more-container").remove(); // if you want to clean >);
.container < width: 300px; >.text-content < max-height: 100px; overflow: hidden; >.show-more-container < background: linear-gradient(0deg, rgba(255,255,255,1) 30%, rgba(255,255,255,0) 100%); margin-top: -40px; height: 40px; padding: 5px; text-align: center; z-index: 2; position: relative; >.container.opened .show-more-container < display: none; >.container.opened .text-content < max-height: initial; /** max-height: 99999rem; some old browsers? */ >
Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de textos y los mezcló de tal manera que logró hacer un libro de textos especimen. No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum.
How to create a «show more» button and specify how many lines of text can be initially shown
I’m looking for a way to create a slide out ‘show more’ feature on my responsive site, which cuts off after two lines of a paragraph. I’ve achieved this before with a static website, by applying a set height to the container and using overflow: hidden , and then animating the height of the container. But being responsive, the container squashes the text at different browser widths, so the text might take up more/less room. Also there may be different content above the paragraph each time pushing it down. So the setting height might not cover two lines exactly. Please check out this jsFiddle: http://jsfiddle.net/XVAzU/ if you need to demonstrate. So I need to cut off after two lines of the paragraph, no matter what width the container is or what comes before or after that paragraph. Thanks for looking!
Using CSS you can apply line-height: 1em and height: 2em which should always show two lines. I don’t know about cross-browser compatibility but the DEMO I attached to my answer shows only two lines of the text as expected in Chrome, FireFox, IE9 and IE8.
4 Answers 4
Starting from your fiddle and wrapped the content into a with a default class of content , used for selection and a class called hideContent which will be swapped with showContent when clicking the show more/show less link.
I also removed the
the text was in. The text is now within the content-div and we are also now able to apply correct height and line-height settings.
I’m assuming setting the line-height will ensure it is the same in all browsers. I’m not 100% certain on that though.
I attached a click event to the «show more» link which switches the classes on the div using jQueryUI switchClass():
$(".show-more a").on("click", function() < var $this = $(this); var $content = $this.parent().prev("div.content"); var linkText = $this.text().toUpperCase(); if(linkText === "SHOW MORE")< linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); >else < linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); >; $this.text(linkText); >);
JsFiddle Demo — show more / show less and applying line-height and animation
$(".show-more a").on("click", function() < var $this = $(this); var $content = $this.parent().prev("div.content"); var linkText = $this.text().toUpperCase(); if (linkText === "SHOW MORE") < linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); >else < linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); >; $this.text(linkText); >);
div.text-container < margin: 0 auto; width: 75%; >.hideContent < overflow: hidden; line-height: 1em; height: 2em; >.showContent < line-height: 1em; height: auto; >.showContent < height: auto; >h1 < font-size: 24px; >p < padding: 10px 0; >.show-more
The above code is an example only but should get you started into the right direction.
I was working on something similar, but i think i like your solution more. Just as an alternative jsfiddle.net/XVAzU/4. I would set the initial class to showContent though, and replace it with the hideContent class in js on load of the document, just for people that have js disabled.
@owen: Let me know if this is what you were looking for or if you need any additional help with that.
@François Wahl, looking at your jsFiddle, it looks perfect! Thank you for the time you put into this. I haven’t had time myself to test it on the actual site yet, something urgent has come up, but I’m going to mark the answer as correct, as the jsFiddle is just what I was looking for.
If you’re searching for a css only solution check this out:
Show less Show more Lorem Ipsum is simply dummy text of the printing and typesetting industry.
.show-hide-text < display: flex; flex-wrap: wrap; >.show-hide-text a < order: 2; >.show-hide-text p < position: relative; overflow: hidden; max-height: 60px; // The Height of 3 rows >.show-hide-text p < display: -webkit-box; -webkit-line-clamp: 3; // 3 Rows of text -webkit-box-orient: vertical; >.show-less < display: none; >.show-less:target < display: block; >.show-less:target ~ p < display: block; max-height: 100%; >.show-less:target + a
My suggestion to solve the problem
$("#slider_desc_toogler").on( "click", function() < $('#slider_desc_toogler >i').toggleClass('fa-arrow-circle-down') $('#slider_desc_toogler > i').toggleClass('fa-arrow-circle-up') if ($("#slider_desc_toogler > i").hasClass( "fa-arrow-circle-down" )) < $(".slider_desc").css("max-height","38px"); >else $(".slider_desc").css("max-height","500px"); >);
.slider_desc < margin: 16px; margin-top: 0px; color: #333333; font-family: Arial; font-size: 14px; line-height: 18px; text-align: justify; overflow: hidden; transition: all 0.5s ease 0s; max-height: 38px; >#slider_desc_toogler < border-top: silver 1px dotted; margin-bottom: 30px; margin-top: 20px; width: 70%; margin-left: auto; margin-right: auto; >#slider_desc_toogler i
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Showing more text with jquery
I am looking for a way to show more or less text. I want to show 600 characters by default and if show more is clicked it will show 600 more characters and then if clicked again shows 600 more until there are no more characters. I also would like a show less button to collapse the text back to its default 600 characters. I have pages with 5000+ words and this would make reading much easier and make it look nicer. Right now I am using this to show the first 600 chars and when show more is clicked it expands all the way.
$(document).ready(function() < var showChar = 600; var ellipsestext = ". "; var moretext = "View more"; var lesstext = "View less"; $('.more').each(function() < var content = $(this).html(); if(content.length >showChar) < var c = content.substr(0, showChar); var h = content.substr(showChar-1, content.length - showChar); var html = c + ''+ellipsestext+' ' + h + ' '+moretext+''; $(this).html(html); > >); $(".morelink").click(function() < if($(this).hasClass("less")) < $(this).removeClass("less"); $(this).html(moretext); >else < $(this).addClass("less"); $(this).html(lesstext); >$(this).parent().prev().toggle(); $(this).prev().toggle(); return false; >); >);
Could somebody please edit this code to work like this or help me to achieve this any other way? I would really like to make my pages more presentable and readable and this would definitely do the trick. Thanks.
Sounds like pagination is far more appropriate, and as a user, I would find this functionality kind of annoying, just my opinion though.
Well I would like it this way so I can show more content on a page and have several instances of the show more which would make things look nice. If it were for a single article on a page I could see it being annoying. I will look into pagination for this but I figured some sore of javascript or jquery with some sort of infinite loop or something on the text would work. I have never even seen a function like this before.
Won’t this be incredibly slow? Anyway, why do it with characters? It would be much easier to do it with height of the box. You could just slide it to expand it every time. (and I kind of agree with the others, sounds like an odd solution. Content is king, don’t hide it away)