show more/Less text with just HTML and JavaScript

前端 未结 8 2111
心在旅途
心在旅途 2020-12-10 04:45

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 CS

8条回答
  •  情歌与酒
    2020-12-10 05:16

    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.

    More on if statements here.

    JSFiddle: http://jsfiddle.net/8u2jF/

    Javascript:

    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"
        }
    }
    

提交回复
热议问题