[javascript] 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:

<html>
<head>
<script type="text/javascript" src="moreless.js"></script>
</head>

<body>
Lorem ipsum dolor sit amet
<p>

<p id="textarea"><!-- This is where I want to additional text--></div>
</p>

<a onclick="showtext('text')" href="javascript:void(0);">See More</a>
<p>
Here is some more text 
</body>
</html>

and my JavaScript is (moreless.js):

function showtext()
{
var text="Here is some text that I want added to the HTML file";
document.getElementById("textarea").innerHTML=text;
}

This question is related to javascript html

The answer is


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';        
    }
}

The complete working example is here: http://jsfiddle.net/akhikhl/zLA5K/


This is my pure HTML & Javascript solution:

var setHeight = function (element, height) {
    if (!element) {;
        return false;
    }
    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<arrayLength; index++){
        toggleButtonsArray[index].onclick = applyToggle(elementHeight);
    }
}

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:

<div class="shorten-text">Your long text goes here...</div>

Hope this Code you are looking for HTML:

            <div class="showmore">
                <div class="shorten_txt">
                    <h4> #@item.Title</h4>
                    <p>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 </p>
                </div>
            </div>

SCRIPT:

    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 = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
        '</span></span><span class="morecontent_txt">' + h
        + '</span>';
        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;
    });

Try to toggle height.

function toggleTextArea()
{
  var limitedHeight = '40px';
  var targetEle = document.getElementById("textarea");
  targetEle.style.height = (targetEle.style.height === '') ? limitedHeight : '';
}

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

<p>Here is text that is originally displayed</p>

<div id="div1">
<p style="color:red;" onclick="showFunction('div2','div1')">show more</p></div>
<div id="div2" style="display:none">

<p>Put expanded text here</p>

<p style="color:red;" onclick="showFunction('div1','div2')">show less</p></div>

<p>more text</p>

Here is the Script:

<script>
function showFunction(diva, divb) {
    var x = document.getElementById(diva);
    var y = document.getElementById(divb);
          x.style.display = 'block';
          y.style.display = 'none';
}
</script>

With some HTML changes, you can absolutely achieve this with CSS:

Lorem ipsum dolor sit amet
<p id="textarea">
    <!-- This is where I want to additional text-->
    All that delicious text is in here!
</p>
<!-- the show/hide controls inside of the following
     list, for ease of selecting with CSS -->
<ul class="controls">
    <li class="show"><a href="#textarea">Show</a></li>
    <li class="hide"><a href="#">Hide</a></li>
</ul>

<p>Here is some more text</p>

Coupled with the 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 {
    display: inline-block;
}

JS Fiddle demo.

Or, you could use a label and an input of type="checkbox":

Lorem ipsum dolor sit amet
<input id="textAreaToggle" type="checkbox" />
<p id="textarea">
    <!-- This is where I want to additional text-->
    All that delicious text is in here!
</p>
<label for="textAreaToggle">textarea</label>

<p>Here is some more text</p>

With the CSS:

#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 {
    content: 'Hide ';
}

JS Fiddle demo.


 <script type="text/javascript">
     function showml(divId,inhtmText) 
     {  
        var x = document.getElementById(divId).style.display; 

        if(x=="block")
        {
          document.getElementById(divId).style.display = "none";
          document.getElementById(inhtmText).innerHTML="Show More...";
        }
       if(x=="none")
       {
          document.getElementById(divId).style.display = "block";
          document.getElementById(inhtmText).innerHTML="Show Less";
        }
     }
</script>

 <p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

if more div use like this change only 1 to 2

<p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

demo jsfiddle