-1

I have a card with text, which is formed using text truncate depending on the width of the div. I need to make: if the text is truncated, then the button "show more" appears, respectively, if all the text is displayed, then the button disappeared. The problem is that methods like: textContent, innerText, ...lenght, etc. read the text from the page code, but it's always full there.

Xaero
  • 3
  • 4

1 Answers1

0

Basically:

.scrollWidth represents the total width of the content inside the content element, including any overflow or hidden content. It considers the entire width, regardless of whether it is visible within the parent container or not.

.clientWidth represents the visible width of the card element, which is the width available for content to be displayed within the card.

So you can check if the text should be truncated or not by comparing these values. Considering you have a react tag in your question, your code looks similar to these:

import React, { useState, useEffect } from 'react';

function Card() {
  const [isTextTruncated, setIsTextTruncated] = useState(false);

  useEffect(() => {
    const checkTextTruncation = () => {
      const card = document.getElementById('card');
      const content = document.getElementById('content');
      const showMoreButton = document.getElementById('showMoreButton');

      const isTruncated = content.scrollWidth > card.clientWidth;
      setIsTextTruncated(isTruncated);

      if (isTruncated) {
        showMoreButton.style.display = 'block';
      } else {
        showMoreButton.style.display = 'none';
      }
    };

    checkTextTruncation();

    window.addEventListener('resize', checkTextTruncation);
    return () => {
      window.removeEventListener('resize', checkTextTruncation);
    };
  }, []);

  const showMore = () => {
    const content = document.getElementById('content');
    content.style.whiteSpace = 'normal';
    content.style.textOverflow = 'clip';
    setIsTextTruncated(false);
  };

  return (
    <div id="card">
      <div id="content">
        {/* Render your text content here */}
      </div>
      {isTextTruncated && (
        <button id="showMoreButton" onClick={showMore}>
          Show More
        </button>
      )}
    </div>
  );
}

export default Card;

Sunny
  • 708
  • 1
  • 4
  • 21
  • This answer looks like it was generated by an AI (like ChatGPT), not by an actual human being. You should be aware that [posting AI-generated output is officially **BANNED** on Stack Overflow](https://meta.stackoverflow.com/q/421831). If this answer was indeed generated by an AI, then I strongly suggest you delete it before you get yourself into even bigger trouble: **WE TAKE PLAGIARISM SERIOUSLY HERE.** Please read: [Why posting GPT and ChatGPT generated answers is not currently allowed](https://stackoverflow.com/help/gpt-policy). – tchrist Jul 17 '23 at 02:21