Search code examples
javascripthtmlsubstringinnertext

How do i undo a substring (like return a text back to its normal length)


please can you help me out on how to undo a substring, cause i want to make the text return to its normal length when i click on a button(span) and also to make the button disappear after its been clicked using javascript this is the code i tried using

HTML

<p class="bio">
   Lorem ipsum dolor sit amet, hello how consectetur 
   adipisicing elit. Sint consectetur provident magni 
   yohoho consequuntur, voluptatibus ghdfff exercitationem 
   at quis similique. Optio, amet!
</p>

Javacript

let bio = document.querySelector('.bio');
const bioMore = document.querySelector('#see-more-bio');
const bioLength = bio.innerText.length;

function bioText() {
   bio.innerText = bio.innerText.substring(0, 100) + "...";
   bio.innerHTML += `<span onclick='addLength()' id='see-more-bio'>See More</span>`;
}
console.log(bioLength)

bioText();

function addLength() {
   bio.innerText = bio.innerText.substring(0, bioLength);
   bioMore.style.display = "none";
}

Solution

  • Another option you could do would be to break the parts apart and put them in spans that conditionally show what needs to be shown. Then flip the visibility when the option is clicked.

    [...document.querySelectorAll('.bio')].forEach(bio => {
      if (bio.innerText.length <= 100) return;
      
      const more = `
        <span class="ellipsis">...</span>
        <span class="more">${bio.innerText.slice(100)}</span>
        <a href="#" class="show-more">Show More</a>
      `;
      
      bio.innerHTML = bio.innerText.slice(0, 100) + more;
      
      bio.querySelector('.show-more').addEventListener('click', e => {
        e.target.parentNode.classList.add('show-more');
      });
    });
    .bio:not(.show-more) .more { display: none; }
    .bio.show-more .ellipsis, .bio.show-more .show-more { display: none; }
    <p class="bio">
       Lorem ipsum dolor sit amet, hello how consectetur 
       adipisicing elit. Sint consectetur provident magni 
       yohoho consequuntur, voluptatibus ghdfff exercitationem 
       at quis similique. Optio, amet!
    </p>
    
    <p class="bio">
       Lorem ipsum dolor sit amet, hello how consectetur 
       adipisicing elit. Sint consectetur provident magni 
       yohoho consequuntur, voluptatibus ghdfff exercitationem 
       at quis similique. Optio, amet!
    </p>