The height of the div is set to zero within the $(document).ready() function

From what I understand, when we write JQuery code inside $(document).ready(), the code will only be executed after the DOM has finished rendering.

I encountered an issue where I was trying to calculate the height of a div inside $(document).ready() but it kept returning zero. Surprisingly, when I ran the same code in the browser's console, it returned the correct height.

The content is being loaded through AngularJS.

JQuery:

$(document).ready(function (){
    // hide view more button if user bio content is less than 200 words
    var userBioLength = $('.userBioText > p').html().split(" ").length;
    if( userBioLength <= 200){
        $('.userBioOverly').addClass("hide");
        $('.viewMore').addClass("hide");

        var textHeight = $(".userBioText").height();
        console.log(textHeight);  // returns 0
        $('.userBioWrapper').css({ height: textHeight + 10 + 'px' });
    }
});

HTML:

<div class="userBioWrapper">
    <div class="userBioText">
        <p>
            {{userInfo.bio}} 
            Lorem ipsum dolor sit amet consectetur adipisicing elit.
            Id fugiat praesentium molestias aliquam quam cupiditate officiis eligendi dolor repellendus,
            recusandae voluptatem. Iste aliquam itaque rem tempore officia perspiciatis natus molestiae.
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Id fugiat praesentium molestias
            aliquam quam cupiditate officiis eligendi dolor repellendus, recusandae voluptatem.
            Iste aliquam itaque rem tempore officia perspiciatis natus molestiae.
        </p>
    </div>
    <div class="userBioOverly"></div>
</div>

I'm puzzled by this inconsistency in behavior. Could I possibly be making a mistake somewhere?

Answer №1

Negative.

The content is not fully rendered, however, the event ready of the document signifies that everything has been downloaded from the server, including the raw HTML.

In the sequence of events, AngularJS actually begins after jQuery's ready state concludes...

If you require a task to be executed after AngularJS has finished processing, you must include a timeout in your controllers or directives; typically, this will function even with a 0ms delay unless an ng-for loop is present.

EDIT: For additional solutions, visit this link (superior to my own suggestions..)

Answer №2

I found success by adjusting the height of the Div using a CSS class. Within the CSS class, I specified the height to be set as auto.

Here is the CSS code:

.unsetHeight { 
    height: auto;
 }

And here is the JQuery script:

 var userBioLength = $('.userBioText > p').html().split(" ").length;
    if( userBioLength<=200){
        $('.userBioOverly').addClass("hide")
        $('.viewMore').addClass("hide")

        $('.userBioWrapper').addClass("unsetHeight");
 } 

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

I'm curious about this specific expression in express.js - can you explain its significance?

Could you please provide a thorough explanation of the following line of code in NodeJS: var app = module.exports = express.createServer(); ...

Is there a way to incorporate locales in calculations involving percentages?

Given the number 4030.146852312 I want to retrieve the four decimal places from this number, resulting in: 4030.1468 Furthermore, I need to format this number according to the specified locale. For example: 4.030,1468 What is the best way to achieve thi ...

Backdrop styling for Material-UI dialogs/modals

Is there a way to customize the semi-transparent overlay of a material-ui dialog or modal? I am currently using material-ui with React and Typescript. https://i.stack.imgur.com/ODQvN.png Instead of a dark transparent overlay, I would like it to be transp ...

Convert h264 video to GIF using Node.js

Currently, I'm utilizing the "pi-camera" library to successfully record video in a raw h264 format on my Raspberry Pi. However, I am encountering an issue with the node.js library "gifify" which keeps throwing the error "RangeError: Maximum call stack ...

Guide on how to load just the content section upon clicking the submit button

Here is an example of my code: <html> <head> <title>Test Loading</title> </head> <body> <div id="header"> This is header </div> <div id="navigation" ...

Is it more efficient to declare a variable or directly return the variable from the Element's getText() promise in Protractor?

I am facing a scenario where I need to retrieve the text of a web element using a promise and then extract a specific part of the string for further processing. Which example, the one at the top or the bottom, should I use? var id = element(by.binding( ...

Using ng-repeat in AngularJS to stream data through a filter

I have the data but I want to retrieve the amount in EUR instead of USD. Is there a way to do this? [{"currency":"USD","amount":3260}, {"currency":"EUR","amount":"320.00"}] This is my current code: <div class="col-xs-6"> <h5 ng-rep ...

What is the best way to apply filtering to my data source with checkboxes in Angular Material?

Struggling to apply datatable filtering by simply checking checkboxes. Single checkbox works fine, but handling multiple selections becomes a challenge. The lack of clarity in the Angular Material documentation on effective filtering with numerous element ...

Tips for setting the id parameter on the asp-route-id for the modal button

My code is causing me some trouble. I have a table with 3 columns: category, subcategories and actions. In the third column, I display buttons "Edit" and "Delete". Here is a snippet of my code: <tbody> @foreach (var category in Model.ToList() ...

Why is my React app opening in Google Chrome instead of the API?

I have a link in my React app that is supposed to open a PDF in another page, but for some reason Google Chrome is redirecting me to the React application instead of opening the API endpoint that renders the PDF. The URL for the PDF is /api/file/:_id and m ...

Troubleshooting issues with cloning a row using jquery

I'm having trouble figuring out why my code isn't working. I want to duplicate a div and add it to the beginning of its parent div. Here's the code I have so far: //Adding a new row function addRow(btn) { var CopiedRow = $(this).closest( ...

Using Node.js to write data to a JSON file

Currently, I am working on a program that scans through an array containing numerous links. It reads through each link, extracts specific text, and then stores it in an output file as JSON. However, I am facing an issue with formatting the JSON file. The ...

Automating the process of posting a file to a form with javascript

I have a piece of client-side JavaScript that creates a jpeg file through HTML5 canvas manipulation when the user clicks an "OK" button. My goal is to automatically insert this jpeg output into the "Upload Front Side" field in a form, simulating a user up ...

Utilizing SCSS Interpolation within a mixin invocation

My goal is to incorporate a simple interpolation into a mixin call: $shapes: "square", "square-green", "circle"; $platforms: "facebook", "twitter", "linkedin", "gplus", "feed"; @each $shape in $shapes { @include sprite-#{$shape}; @each $platform ...

The three.js library is throwing an error because it is unable to access the 'geometry' property of an

function CreateNewSphere(x, z) { var sphereGeometry = new THREE.SphereBufferGeometry(10 * factor, 32, 32); var sphereMaterial = new THREE.MeshBasicMaterial({ color: SphereColor, wireframe: false }); var sphere = new THRE ...

Why is it that I am unable to properly encode this URL in node.js?

$node querystring = require('querystring') var dict = { 'q': 'what\'s up' }; var url = 'http://google.com/?q=' + querystring.stringify(dict); url = encodeURIComponent(url); console.log(url); Here is the re ...

Scrolling up the page following the addition of a new row

https://i.sstatic.net/QLBEe.png Description After clicking the plus button in the image above, a new row is created using jQuery autocomplete. https://i.sstatic.net/Xf5Et.png Description The image above illustrates the page displaying when scrolled to t ...

Tips on extracting the value from an HTML input control

Looking for some assistance with a table generated by a 3rd party control. The table consists of only one row and one column containing HTML text like this: <p> this is a test</p> <p> <input name="amount" type="text" value="th ...

Encountering the error message ERR_CONNECTION_TIMED_OUT while using Vue CLI

Currently, I am venturing into the world of Vuex and attempting to incorporate some API requests using this state management pattern. Here is the structure I have set up: Component.Vue export default { created() { this.$store.dispatch('getDat ...

Enhance the php query limit using javascript when loading additional content

Hey there, currently working on implementing a reverse infinite scroll feature for a private messaging module. Everything seems to be functioning well, except for one issue I'm facing - struggling to update the query limit. I set the maximum and lim ...