How can JavaScript be used to toggle the visibility of text on a webpage

Can anyone help me with a problem I'm having toggling text? I have a truncated text and I want to be able to switch back and forth between the truncated text and the original text on button click.

Here is a link to the pen.

var myButton = document.getElementById('toggle_text')
var text = document.getElementById('original_text')
console.log(text)

var truncate = function(elem, limit, after) {

  // Make sure an element and number of items to truncate is provided
  if (!elem || !limit) return;

  // Get the inner content of the element
  var content = elem.textContent.trim();

  // Convert the content into an array of words
  // Remove any words above the limit
  content = content.split(' ').slice(0, limit);

  // Convert the array of words back into a string
  // If there's content to add after it, add it
  content = content.join(' ') + (after ? after : '');

  // Inject the content back into the DOM
  elem.textContent = content;

};

var elem = document.querySelector('.truncate');
truncate(elem, 7, '...');


function switchText() {

}
<div class="truncate" id="original_text">
  Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>

<div>
  <button id="toggle_text" onClick='switchText()'>Toggle Between truncate and Original Text</button>
</div>

Appreciate any help on this. Thanks in advance.

Answer №1

To store the entire content text along with the truncated state, you can create variables in the following manner:

var displayButton = document.getElementById('toggle_display')
var textContent = document.getElementById('full_textContent')
console.log(textContent)

var truncateText = function(element, limit, appendix) {

  // Ensure that an element and limit for truncation are provided
  if (!element || !limit) return;

  // Retrieve the inner content of the element
  var content = element.textContent.trim();

  // Convert the content into an array of words
  // Remove any words beyond the specified limit
  content = content.split(' ').slice(0, limit);

  // Convert the array of words back to a string
  // Append the specified text after truncation, if any
  content = content.join(' ') + (appendix ? appendix : '');

  // Update the DOM with the truncated content
  element.textContent = content;
  isTruncated = true;
};

var selectedElement = document.querySelector('.truncated-section');
var fullContent = selectedElement.textContent;
var isTruncated = false;
truncateText(selectedElement, 8, '...');


function toggleContent() {
    var selectedElement = document.querySelector('.truncated-section');
    if (isTruncated) {
      selectedElement.textContent = fullContent;
      isTruncated = false;
    } else {
      truncateText(selectedElement, 8, '...');
    }
}
<div class="truncated-section" id="full_textContent">
  Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>

<div>
  <button id="toggle_display" onClick='toggleContent()'>Toggle Between Truncated and Full Text</button>
</div>

Answer №2

You can achieve the same result with a more concise code:

const btn = document.getElementById('toggle_text');
const originalText = document.getElementById('original_text');
const text = originalText.innerText;
const shortText = text.substring(0, 7) + '...';

btn.addEventListener('click', function() {
  if (originalText.innerText === text) {
    originalText.innerText = shortText;
  } else {
    originalText.innerText = text;
  }
}, false);
<div class="truncate" id="original_text">
  Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>

<div>
  <button id="toggle_text">Toggle Between truncate and Original Text</button>
</div>

Answer №3

If you're looking for insights, it might be worthwhile to check out S.Serpooshan's solution to a similar query. Oftentimes, achieving this goal can be as simple as using CSS alone, which offers a more efficient way to manage the page's status.

Instead of storing your text as a JavaScript variable, you can opt to conceal it from the Document Object Model (DOM) while still maintaining easy access to it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

Steps for inserting a button within a table

Currently, I have implemented a function that dynamically adds the appropriate number of cells to the bottom of my table when a button is clicked. This is the JavaScript code for adding a row: <a href="javascript:myFunction();" title="addRow" class= ...

Even though I have the image button's ID, I am unable to successfully click on it

I am facing an issue where I can't seem to click on an image button even though I know its ID: driver.findElement(By.id("its Id")).click() Unfortunately, I cannot provide the website link as it is not a public website. However, I have pasted the HTM ...

Issue with Material UI tabs: TypeError - Unable to access property 'charAt' as it is undefined

Currently, I am attempting to implement Material UI tabs in my project. Here is the component in question: const ItemssOverview = ({ details }) => { if (details && details.items) { return ( <div> &l ...

A guide on using JavaScript to obtain the original calculation for a specific equation once a checkbox has been unchecked

I am facing a scenario where I have two input fields. One should display the value of Quantity, and the other should display the value of Price. The first input, which is for quantity and of type number, has the disabled attribute. However, upon checking a ...

What is the best way to blend a portion of an image into a div?

Having a bit of trouble with overlapping my image onto another div in my current project. When you take a look at what I've been working on, you'll see there's an image that says "That's me!" and it needs to overlap the left side div. I ...

how to ensure a consistent property value across all scopes in AngularJS

Here is my perspective <div ng-if="isMultiChoiceQuestion()"> <li class="displayAnswer" ng-repeat="choice in getMultiChoice() track by $index" ng-if="isNotEmpty(choice.text.length)"> <input type= ...

Using a computed property setter in Vue.js/Javascript while focusing on a datepicker can lead to crashing the browser

Can anyone explain why my javascript / vuejs code is crashing on my JSFiddle when I focus on the start date datepicker (causing the browser to hang)? If you uncomment the endDate computed property and comment out the current one, it works fine but the fun ...

Click on any checkbox to select all checkboxes at once

I have created a table with each column containing a checkbox. My goal is to select all checkboxes in the table when I click on the checkbox in the top row (th). Can someone guide me on how to achieve this? Below is my code: <table style="width:100%"& ...

Using JavaScript to retrieve the updated timestamp of a file

Can JavaScript be used to retrieve the modified timestamp of a file? I am populating a webpage with data from a JSON file using JavaScript, and I want to display the timestamp of that file. Is there a way to do this using only JavaScript? ...

Remove the div of the previous selection in jQuery and add the current selection by appending it, ensuring only one selection per row is allowed when

Here is a code snippet that includes buttons appending selections to the "cart" div upon clicking. The first script ensures only one selection per row when multiple buttons in the same row are clicked. In the second script, selections are appended to the ...

Avoid working on the script for the element in the partial view during the event

In my index.cshtml view, I have a script that triggers an AJAX call when the SearchingManagerId2 element is changed. $("#SearchingManagerId2").on("change", function () { var valueForSearch = $(this).val(); $.ajax({ ...

Action of Submit Button Based on Field Matching Another Form

I currently have a single page that contains two forms, with only one form being displayed at the moment. The concept is that if the user selects a specific state from the drop-down menu and clicks on the submit button, they will be redirected to either a ...

Combining two different arrays in JavaSscript to create a single array

I have two arrays, one representing parents and the other representing children in a relational manner. I need to combine these into a single array. Parent array: const cat = ['a','b','c']; Child array: const sub =[{name:&ap ...

What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator? I've attempted to utilize subjects without success. Below is my current code. import { Subject } from 'rxjs'; import { Component, Output } ...

What is the most efficient way to perform multiple socket writes using a single active socket connection to an Express web server?

Attempting to perform multiple write requests using a single active socket connection to an express server running on localhost. This is done by making an HTTP request to an express web server on localhost with the following message: GET /temp?sensorId=1& ...

I have just started a new project in Vue and noticed that the app div has some extra margin around it. Can anyone

In my fresh Vue project, I have the following code: App.vue: <template> <div id="app"> <p>hello</p> </div> </template> <script> export default { name: 'App', components: { } ...

Error: $this.text is throwing a TypeError and is not working as a function

Upon examining the code below: var $this = $(this).children('div.submenu1').children('a.subtile')[0], title = $this.text(), name = $this.attr('node').val; An error is encountered: Uncaught TypeError: $this.text is not a fun ...

positioning of multiple buttons in a customized header for mui-datatables

I'm currently using mui-datatables in my app and have customized the table toolbar to include additional buttons. However, I've encountered an issue where adding a second button causes it to be displayed below the first one, despite there being e ...

Fading colored images and backgrounds using Javascript

Although js and html are not my strong points, I am attempting to create two simple effects on a single page. As the user scrolls down the page, I want the background image or color to change as different divs come into view and then move off the screen. ...