dotdotdot.js is only functional once the window has been resized

For my website, I am attempting to add an ellipsis to multiline paragraphs that exceed a certain height. I have incorporated the dotdotdot jquery plugin from here.

An odd issue arises when the page is refreshed, as the ellipsis does not appear until I resize the window. Despite rearranging the script placement in my html file so that dotdotdot loads last, the problem persists. Any insights on why this might be happening?

The settings utilized for dotdotdot are as follows:

$(document).ready(function() {
    $("p.article-content").dotdotdot(
    {
        /* The HTML to add as ellipsis. */
        ellipsis : '...',

        /* How to cut off the text/html: 'word'/'letter'/'children' */
        wrap : 'word',

        /* jQuery-selector for the element to keep and put after the ellipsis. */
        after : null,

        /* Whether to update the ellipsis: true/'window' */
        watch : true,

        /* Optionally set a max-height, if null, the height will be measured. */
        height : null,

        /* Deviation for the height-option. */
        tolerance : 0,

        /* Callback function that is fired after the ellipsis is added,
        receives two parameters: isTruncated(boolean), orgContent(string). */
        callback : function( isTruncated, orgContent ) {},

        lastCharacter : {
            /* Remove these characters from the end of the truncated text. */
            remove : [ ' ', ',', ';', '.', '!', '?' ],

            /* Don't add an ellipsis if this array contains
            the last character of the truncated text. */
            noEllipsis : []
        }
    });
});

The displayed HTML structure (experimental layout):

<article class="article">
  <div class="article-image"></div>
  <h2>Title</h2>
  <p class="date">December 19, 2012</p>
  <p class="article-content">Lorem ipsum etc. (the actual content is larger)</p>
</article>

Here's the accompanying CSS:

article {
  font-size: 99%;
  width: 28%;
  line-height: 1.5;
  float: left;
  margin-left: 8%;
  margin-bottom: 3em;
  text-align: justify;
}

article h2 {
  font-size: 125%;
  line-height: 0.5;
  text-transform: uppercase;
  font-weight: normal;
  text-align: left;
  color: rgba(0,0,0,0.65);
}

.date {
  margin-top: 0.3em;
  margin-bottom: 1em;
  font-family: 'PT Sans';
  color: rgba(0,0,0,0.5);
}

.article-image {
  background-image: url(http://lorempixel.com/g/400/300/city/7);
  width: 100%;
  height: 13em;
  overflow: hidden;
  margin-bottom: 1.5em;
}

p.article-content {
  font-family   : 'PT Sans';
  color         : rgba(0,0,0,0.65);
  margin-bottom : 0;
  height        : 7em;
  overflow      : hidden;
}

Answer №1

Encountered a comparable issue. Ended up resolving it by placing the dotdotdot initialization within a window load event handler instead of the traditional dom ready event.

Answer №2

When I first started using dotdotdot, everything seemed simple. However, I encountered an issue with responsive pages that had a lot of content. Even after the document was ready, the containers on the page were still resizing as the content filled in.

$(document).ready(ellipsizeText);        // The plugin seemed to be working perfectly here as described in the documentation.
window.setTimeout(ellipsizeText, 400);   // Just to be safe.
window.setTimeout(ellipsizeText, 800);   // In case the user didn't notice any flickering.
$(window).load(ellipsizeText);           // Oh no! The images are still loading, so not all containers are in their correct positions yet. We need to wait for them.
function ellipsizeText()
{
    $(".selectorForEllipsis").dotdotdot({
        watch: true
    });
}

I believe the best solution would be to add a listener to every container with text to update dotdotdot when its position or size changes, rather than just relying on window resize. Perhaps using Ben Alman's jQuery resize plugin could help with this.

Is there a plugin available that handles these content loading issues more effectively?

Answer №3

A different approach could be to enclose the whole function within a .resize() function. This may not be the most elegant solution, but it should get the job done:

$(document).ready(function() {
    $(window).resize(function()
    {
        $("p.article-content").dotdotdot(
        {
            // Insert all your code here
        });
    }).resize();

    // The second .resize() call will trigger once the document is ready (i.e. onload),
    // consequently executing .dotdotdot() upon loading
});

[Update]: Following Kevin's advice, considering that .dotdotdot() already monitors the resize event, there is no need for wrapping the function. Simply initiate the event when the document is ready, using $(window).resize().

Answer №4

I made a simple tweak by updating watch: "window" to watch: true

and surprisingly, it resolved the issue I was facing!

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 your Z-Index failing to make an impact?

Currently, I am attempting to layer divs on top of a background image. All the elements have designated position attributes, and I have applied a 50% opacity to the background image so that what's behind it is partially visible. Despite setting the z- ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

Manipulating Objects with CSS Transform in Global/Local Coordinates

If we take a closer look at our setup: <div id="outside"> <div id="inside">Foo</div> </div> and apply a rotation to the outer element - let's say turning it 45 degrees clockwise: <div id="outside" style="transform: ro ...

Calculation Error in JavaScript/JQuery

I've been working on a JavaScript function to calculate the sum of values entered into textboxes, but it seems to be giving me inaccurate results in certain cases. Check out the FIDDLE here Enter values : 234.32 and 32.34 Result: 266.6599999999999 ...

Sharing JSON data between PHP and JavaScript/AJAX

In order to validate strings on my website, I am developing a validation mechanism using both Javascript and ajax for client-side validation and PHP for server-side validation. It is essential for both PHP and Javascript to utilize the same variables, suc ...

Discussing the use of local identification within a <BASE> tag in SVG specifically on the Firefox browser

Encountering an issue on a current Firefox browser running on Win7 while utilizing SVG (although the details may not be directly related to the problem): ` <head> <!-- base href="http://127.0.0.1/package/index.php" /--> < ...

When using Vue3 along with Axios.post, the data is being serialized incorrectly

Goal: I need to send the data {"username": myuser, "password": mypswd} to an API endpoint in order to receive a token for further communication with the API. The following code snippets attempt to achieve this: // Attempt # 1 let re ...

Display an Asterisk Icon for md-input fields with lengthy labels

Documentation states that md-inputs add an asterisk to the label if it is a required type. However, when input containers have width constraints and long labels, the label gets truncated and the asterisk becomes invisible. From a user experience perspectiv ...

Issue with Bootstrap checkbox buttons not rendering properly

I'm attempting to utilize the checkbox button feature outlined on the bootstrap webpage here in the "checkbox" subsection. I copied and pasted the html code (displayed below) from that page into a jsfiddle, and checkboxes are unexpectedly appearing in ...

Is it possible to conceal the controls on the slick carousel?

Is there a way to prevent slick from automatically adding next and previous buttons? I've tried using CSS to hide them but it doesn't seem to work. <button type="button" data-role="none" class="slick-prev" aria-label="previous" style="displ ...

Encountered an error: data.map is not functioning as expected in the React component

Hi there, I've encountered a small issue with my modal component. The error message I'm getting is: Uncaught TypeError: meatState.map is not a function. Any suggestions on what may be causing this problem? Your assistance would be greatly appreci ...

The v-data-table is unable to fetch the user list information from the API using Axios

How can I solve the issue of displaying "No data available" in the user list data table on my userDirectory page? I have created a userDirectory page with a subheader and a data table from Vuetify, but it seems to have no data available. <template> ...

Ensure that the text inside the button does not exceed its boundaries (utilizing Bootstrap v4)

My current code snippet appears below. <div class="col-xl-2 col-lg-12"> <button class="btn btn-secondary w-100" value=1>But.</button> </div> <div class="col-xl-4 col-lg-12"> <button cla ...

Why do attributes of a directive fail to function within a different directive in AngularJS?

Trying to set attributes of the angularJS directive named ng-FitText within another angularJS directive called scroll-cards. Here's the approach I'm taking: In the code snippet below, the attribute data-fittest is being assigned from ng-FitText ...

Is Python a suitable programming language for developing applications on a Raspberry Pi device?

I'm diving into the coding world for the first time and I have a project in mind - controlling my RC car with my smartphone using a Raspberry Pi 3. Research suggests that I should use Node.JS and JavaScript to create the app, but I'm wondering if ...

Check to see if the event handler is triggered and the promises are executed in sequence (syncronously)

I have a Vue button click handler that, depending on the arguments it receives, can do the following: execute request A only execute request B only execute request A and then request B sequentially (request B is only called if request A completes successf ...

unable to receive input value

<script type="text/javascript" language="javascript"> $(function() { $("#distributor").autocomplete({ source: function(request, response) { $.ajax({ url: "/Devices/autoDistributor", ...

Having trouble figuring out how to update a list using ajax in Yii

I need to modify a JavaScript function that filters the content of a list. The current code looks like this: var id = $(this).data('id'); $.fn.yiiListView.update('contests-list', { data: {category: 2} }); I couldn't find any ...

Products failing to appear in shopping cart

I'm facing an issue with my React Redux Cart setup where items are added to the cart state using the addItem action, but they do not appear on the Cart page. Challenge: After adding items to the cart through the addItem action, I can see the state u ...

Having trouble accessing array elements in react components

When retrieving JSON data for a single student from the server in my React application, I am able to access this.state.info.Firstname but encountering difficulty accessing this.state.info.Father.Firstname. How can I access this information? This is my Rea ...