Show either the abbreviated or complete form of the text

Initially, the default display should show the shortened version of each element (one line with "..." included). All items must consistently be shown in either the shortened or full-length version.

  1. If all items are in shortened mode - clicking on one item should expand all elements to their full length, with each element being the same height, matching the height of the tallest element.
  2. If all items are in full-length mode - clicking on one element should revert all elements back to their shortened version (one line with "...").

I have written the following code to achieve this:

$(document).on("click", ".elementText", function (e) {
if($( this ).css( "-webkit-line-clamp" ) == "1"){
$(this).css("-webkit-line-clamp", "99");
var elementHeight = $(this).css( "height" );
$($(this).parent()).find(".elementText").each(function(){
$(this).css("-webkit-line-clamp", "99");
if($(this).css( "height" ) < elementHeight){
$(this).height(elementHeight);
}
});
}
else{
$(this).css("-webkit-line-clamp", "1");
var elementHeight = $(this).css( "height" );
$($(this).parent()).find(".elementText").each(function(){
$(this).css("-webkit-line-clamp", "1");
if($(this).css( "height" ) > elementHeight){
$(this).height(elementHeight);
}
});
}

});
.elementText{
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
cursor: pointer;
padding-left: 5px;
width:200px;
background:yellow;
float:left;
margin:5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="elementText">
Contrary to popular belief, Lorem Ipsum is not simply random text
</div>

<div class="elementText">       
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.      
</div>

<div class="elementText">           
The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here',
</div>

If the "expand" (first click after page load) and "shorten" (second click after page load) actions are performed on the same element, the code works as intended. However, if the "expand" (first click after page load) and "shorten" (second click after page load) actions are applied to different elements (e.g., expanding the third element and then shortening the first element), an issue arises where the text may not be truncated correctly.

What causes this malfunction and what adjustments should be made to rectify the issue?

Answer №1

The main issue arose when setting the height for the long/short version based on the height of the clicked element. Instead, all elements should be enlarged to find the maximum height, and then the height should be set for all of them to max.
To achieve the short version, set the height to auto so that each element displays only one line. If there are variations in height due to different font sizes, the max step can be applied afterwards.

It may be helpful to test the following: A global variable can be used to store whether the long version is displayed or not. Toggle this variable on each click event. Alternatively, a class can be added and removed from an HTML element.

var long = false;

$(document).on("click", ".elementText", function (e) {
             if(!long){
                long=true;
                let max = 0;
                $(this).css("-webkit-line-clamp", "99");
                $($(this).parent()).find(".elementText").each(function(){
                    $(this).css("-webkit-line-clamp", "99");
                    max = Math.max(max, parseInt($(this).css( "height" )) );
                });
                $($(this).parent()).find(".elementText").each(function(){
                    $(this).height(max);
                });
            }
            else{
                long=false;
                $(this).css("-webkit-line-clamp", "1");
                $(this).height('auto');
                $($(this).parent()).find(".elementText").each(function(){
                    $(this).css("-webkit-line-clamp", "1").height('auto');
                });
            }
        });  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <style> 
            .elementText{
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                cursor: pointer;
                padding-left: 5px;
                width:200px;
                background:yellow;
                float:left;
                margin:5px;
            }           
        </style>        
    </head>
        <body>
    
        <div class="elementText">
            Contrary to popular belief, Lorem Ipsum is not simply random text
        </div>
        
        <div class="elementText">       
            It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.        
        </div>
        
        <div class="elementText">           
            The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here',
        </div>
</body>

Answer №2

If you are faced with this particular situation, my suggestion would be to utilize classes instead of directly manipulating the CSS attributes most of the time.

The main objective here was to determine the tallest height among the 3 elements, which is solely based on their content after they have been expanded. This was the challenge at hand.

Below is my proposed solution:

(function(){
  var display_element = $(".elementText");
  
  function getLargestHeight(elemArray)
  {
    // if there's no elements parsed, then no elements are expanded
    if(elemArray.length <= 0)
      return "auto";
      
    var rempResult = 0;
    
    $.each(elemArray,(i, e) => {
      let _e_height = parseInt($(e).css("height").slice(0,-2));
      
      if(_e_height > rempResult)
        rempResult = _e_height;
    });
    
    return rempResult + "px";
  }
  
  display_element.on("click", (e) => {
    if(display_element.hasClass("expanded"))
      display_element.removeClass("expanded");
    else
      display_element.addClass("expanded");
     
    $.each(display_element, (i, e) => {
      $(e).css("height", getLargestHeight($(".expanded")));
    });
  });
})();
.elementText{
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  cursor: pointer;
  padding-left: 5px;
  width:200px;
  background:yellow;
  float:left;
  margin:5px;
  height: auto;
}

.expanded
{
  -webkit-line-clamp: 99;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="elementText">
  Contrary to popular belief, Lorem Ipsum is not simply random text
</div>

<div class="elementText">       
  It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.      
</div>

<div class="elementText">           
  The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here',
</div>

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

Execute javascript code 1.6 seconds following the most recent key release

Is there a more efficient way to execute JS 1.6 after a keyup event, considering that the timer should reset if another keyup event occurs within 1.6 seconds? One possible approach could involve utilizing a flag variable like this: var waiting = false; $ ...

Making API calls using JavaScript

I'm struggling with understanding how to approach this problem in javascript. Here is the question along with the details. I would appreciate any assistance. QUERY We have a server backend that provides two endpoints: /GetLocalPressReleases and /Get ...

Conceal the URL and any parameters upon successful completion of AJAX request

In my ajax js code, the solonreport.jsp file returns a URL link that connects to a local report server and generates an Excel report. However, when using this link with the window.open(json.url) function, the link and parameters are visible to the user. ...

What is the best way to decrease the width of one of the four columns?

I trust all is well with you. I'm having trouble adjusting the width of one of my table data cells. In the image attached below, you'll notice that my + icon is the same size as the other columns. I'd like to make it much narrower and posit ...

Tips for incorporating Action Links into your CSS workflow

<li class="rtsLI" id="Summary"><a href="javascript:void(0);" onclick="javascript:rtsXXX.OnClientTabSelected(this‌​, 0);" class="rtsLink"><span class="rtsTxt">Test</span></a></li> I have made a change by replacing th ...

Exploring search filters using KnockoutJS

I'm currently working on incorporating a search filter into my web application. After reading some informative articles and exploring various Jsfiddles, I've attempted to enable searching by TypeName to display the corresponding row with that spe ...

Gallery Pagination using JQuery is not working properly

I am experimenting with the jquery easy paginate plugin on a separate page of my Blogspot. The images are displaying properly, but the pagination and CSS are not showing up. I need to adjust my CSS to make this jQuery pagination work correctly. Can someone ...

Perform an ajax request to check for the existence of an image and insert

I've been trying to implement asynchronous JavaScript based on guidance from this answer, but I'm facing some difficulties in understanding where things are going wrong. My goal is to use autocomplete functionality to request specific files from ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

Show different values in Array arranged in Table format with the help of Ajax code

Check out the code I have attempted below: <script type="text/javascript"> $('#doctorselected').on('change', function(e){ console.log(e); var doctorid = e.target.value; var url = '{{URL::to('getdoc ...

Ways to extract pertinent information from a PHP API

I've been attempting to add parameters to my query, but I keep getting inconsistent results. Despite trying different methods, I haven't been successful. Take a look at the code below. First, here is my code that functions properly without using ...

Transpiler failed to load

My Angular application running on Node has recently encountered a problem with the transpiler. I have been trying to load mmmagic to evaluate uploaded files, but encountered difficulties in the process. While attempting to update NPM packages, I gave up on ...

Tips for utilizing XMLHttpRequest to instruct a website to take action

Although I have no prior experience with Ajax, I am in need of some guidance to create a simple Chrome extension. Despite searching online, I have not been able to find much information on this topic, which I believe should be straightforward. Request URL ...

Guide to including configuration settings in locals for Sails.js

Currently working on a webapp with Sails.js, I am looking for ways to set up different configurations for development and production modes. Initially, I attempted to store the configuration key in config/local.js, but unfortunately, it did not yield the de ...

"Exploring the use of conditional rendering in React to dynamically hide and show components based

I am currently immersed in the world of React/Redux, focusing on an e-commerce project. This particular application offers two payment methods: cash and card payments. On the product display page, both payment icons are visible. However, I am seeking a sol ...

Four divs containing texts of varying sizes

I have varying sizes of text that I would like to organize into 4 divs in the center of the page, similar to this image http://firepic.org/images/2015-08/22/0b0r536o40es.png However, it seems that my pink div is causing the ones below it to be pushed down ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

Transitioning from Event-driven Object Oriented design to Redux structure

I currently have a structure that is mostly object-oriented and I am considering migrating to React/Redux due to handling issues with events. I have various modules with objects structured like this: User { getName() getSurname() etc... } These obj ...

In Internet Explorer, the toggle div expands to fill the available space, but this behavior is not consistent in

Utilizing the toggle function in jQuery, I created a mechanism to switch between 4 different blocks of content. You can view a demonstration of how the functionality operates correctly in Google Chrome here: If you encounter any issues with the functiona ...

Experimenting with the input type generated by the Form Helper tool

Before generating the form using Form Helper, is there a method to preview the type of input it will produce? I would like to confirm whether it will result in a select or multi-select element before loading the page. ...