How can you call a function in JavaScript based on a condition?

Is there a way to conditionally truncate text using a function called Truncate only when the offsetHeight of the left div with class demo is greater than the offsetHeight of the right div? If this condition is not met, then simply return the original content.

Check out the demo


var textHolder = document.querySelector('.demo');
var textHolder2 = document.querySelector('.demo2')
var textHolderHeight = textHolder.offsetHeight + 'px'
var textHolderHeight2 = textHolder2.offsetHeight + 'px'
console.log(textHolderHeight)
console.log(textHolderHeight2)
var fullText = textHolder.innerHTML;
var btn = document.querySelector('.btn');
var textStatus = 'full'; // use this to check the status of text and toggle;

function Truncate(textHolder, limit) {
  let txt = textHolder.innerHTML;
  if (txt.length > limit) {
    let newText = txt.substr(0, limit) + ' ...';
    textHolder.innerHTML = newText;
    textStatus = 'truncated';
  }
}

Truncate(textHolder, textHolder.offsetWidth / 10);

function toggleText() {
  if (textStatus === 'truncated') {
    textHolder.innerHTML = fullText;
    textStatus = 'full';
  } else {
    Truncate(textHolder, textHolder.offsetWidth / 10);
  }
}

btn.addEventListener('click', toggleText);

<section class="demo" id="demo">
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
  line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>

<button class="readMore btn">Read More</button>
<br><br><br>

<section class="demo2" id="demo2">
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
  line of text so that the words don't wrap when they're not supposed to. Multi-line of course!don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to.
  Multi-line of course!don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>

Appreciate your assistance on this matter.

Answer №1

If you find yourself needing to call Truncate often, you have two options.

if(textHolderHeight > textHolderHeight2){
     Truncate(textHolder, textHolder.offsetWidth / 10);
}

Alternatively, you can streamline your code by incorporating the if statement inside the Truncate function itself.

function Truncate(textHolder, limit) {
  let txt = textHolder.innerHTML;
  if (txt.length > limit && textHolderHeight > textHolderHeight2) {
    let newText = txt.substr(0, limit) + ' ...';
    textHolder.innerHTML = newText;
    textStatus = 'truncated';
  }
}

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

Is real-time updating possible with data binding in Polymer and JavaScript?

I have a scenario where I am working with two pages: my-view1 and my-view2. On my-view1, there are two buttons that manipulate data stored in LocalStorage. On my-view2, there are two simple div elements that display the total value and the total value in t ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

Modifying app aesthetics on-the-fly in Angular

I am currently working on implementing various color schemes to customize our app, and I want Angular to dynamically apply one based on user preferences. In our scenario, the UI will be accessed by multiple clients, each with their own preferred color sch ...

Guide on enabling a plugin for Stylus in a Vue 2 project using the webpack template

I am working on a Vue2 project with the Webpack template and utilizing Stylus as a CSS preprocessor. I'm facing difficulties in applying plugins for Stylus like rupture. I attempted to adjust the options in build/utils.js for the stylus loader by add ...

The browser has disregarded a CSS rule

Hey there, I have a question that may seem silly, but I just can't seem to find the answer anywhere. Please take a look at this fiddle: I need to remove #Navigation in the CSS declaration below: #Navigation .stretch { ... } so it should look like ...

execute various scripts in content_scripts depending on the "matches" provided

I am new to JavaScript and currently working on customizing the script from the MDN tutorial, Your First WebExtension My goal is to draw either a red or blue box around a webpage based on whether it is http:// or https://. But I have encountered a proble ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

Removing an event from Fullcalendar

With the help of a post on StackOverflow, I managed to modify my select: method to prevent users from adding an event on a date before NOW. However, there is a drawback. When a user clicks on an empty time slot and the system displays an alert message, th ...

Learn the step-by-step process of sending an email through the SendGrid API V3 utilizing templates with a comprehensive example

Currently, I am delving into the SendGrid documentation regarding templates and stumbled upon this: You have three options to send transactional templates: Utilizing the SMTP Relay Including the template ID in the templates parameter of the W ...

jQuery fails to function properly when using the .live("keyup") event

Below is the code snippet: $(document).ready(function() { $("#querybox").live("keyup", function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) { $("#querybox").blur(); } else { search(document.getElementB ...

`Certain browsers are experiencing issues with text overlay functionality.`

I have managed to successfully create the necessary code to incorporate an image with a child element containing text overlaying the image. However, this functionality does not appear to be working on Internet Explorer (IE), and I am struggling to find a C ...

Put a spinner within a JavaScript function

Implementing a spinner using JavaScript function. Hello everyone, I am new to JavaScript and I am struggling to include a spinner in my code. Below is the code that I wrote. Can anyone help me identify what the issue might be? document.getElementById(&apo ...

Secure your desktop application with OAuth by enabling HTTPS on localhost

I am currently in the process of developing a desktop application that integrates with Spotify's oauth api using the implicit grant flow as outlined here: My plan is to incorporate an "Authenticate" button, which when clicked will open the user' ...

What are the best situations to utilize bootstrap and when should you avoid it?

When it comes to web development, there is often a debate on whether to use Bootstrap or custom CSS for designing a website. For my school project, I am tasked with creating a homepage and contact page using Bootstrap primarily. However, we are also requir ...

Align the radio button group in the center with corresponding labels

I have several radio buttons with labels that vary in length. I am trying to figure out how to center them horizontally so that the labels are centered on the page, but still appear as if they are left-aligned. Desired result: Current HTML snippet: < ...

The color of the ellipsis value does not match properly

In my table, I have lines that end with 3 dots '...' when the text overflows. To achieve this, I used the ellipsis value of the text-overflow property. While this works well and the '...' are displayed when resizing the window, I encoun ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

Retrieve the website address from a string of HTML code

I'm struggling to extract the URL from a given String that contains an HTTP response with an HREF tag. I've managed to identify the start of the links, but I need to stop the string as soon as the HREF tag ends. How can I accomplish this? public ...

Fill in the username and password on the login page of the website when it is accessed through the mobile application

Currently, I have a Joomla website and mobile App that are hosted on different servers. Both are owned by the same party, and users have accounts on both platforms with identical ID's and passwords (even though they are stored in separate databases, w ...

What is the best way to ensure that form inputs and labels stay aligned?

Let's consider a scenario where there is a web page containing a form: <form> <label for="FirstName">First:</label> <input name="FirstName" type="text"> <label for="MiddleName">Middle:</label> <input n ...