skip to Main Content

I want my <textarea> to auto resize while writing a comment on my wordpress site.

I have tried using js and jquery solutions from different tutorials but none of them seem to work. At first I thought my script.js wasn’t linked properly but i could find it in my source code. I have tried making the <textarea> into <div contenteditable= true> but wordpress does not detect the text for some reason, so it doesn’t let me post comments with this solution

2

Answers


  1. I have tried making the into but wordpress does not detect the text for some reason…

    The best would be to find that reason. But if you don’t know how or don’t want to, there is a quick "hack" that can be done here.

    You will leave the textarea in place, but will add a class to hide it.
    Then, you will add the div contenteditable right next to it.

    And finally, the below script will litterally copy the text content from the div to the textarea in real time.
    So on submit, the textarea will have some content just like before.

    It will work for one or more "replacements".
    Type in the blue div below… 😉

    document
      .querySelectorAll(".textareaReplacement")
      .forEach((textareaReplacement) =>
        textareaReplacement.addEventListener("keyup", (event) => {
          event.currentTarget.previousSibling.value = event.currentTarget.innerText;
        })
      );
    .replaced {
      /* Uncomment that display none. It was necessary to be visible in this demo */
      /* display: none */
    }
    .textareaReplacement {
      /* Style that div to look good */
      border: 1px solid blue;
      width: 300px;
    }
    <textarea class='replaced'></textarea><div class='textareaReplacement' contenteditable='true'></div>
    Login or Signup to reply.
  2. If you want the textarea to resize vertically as the user types in the textarea you can use the scrollheight from the textarea oninput event to set the height of the textarea.

    See example below…

    // our oninput comment textarea resize function
    function commentResize(textarea) {
    
      // reset style height to auto in order to get the current height of content
      textarea.style.height = "auto";
      
      // set the new height based on the comment textarea scroll height
      textarea.style.height = textarea.scrollHeight + "px";
      
    }
    .comment-textarea {
      height: 34px; /* set initial height */
      resize: none; /* stop manual resizing */
      overflow: hidden; /* hide scrollbars */
    }
    <textarea class="comment-textarea" oninput="commentResize(this)"></textarea>

    Here is a jsFiddle version… https://jsfiddle.net/joshmoto/7wv6eo3q/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search