Increase the offsetHeight of the entire class

I am faced with a challenge on my webpage where elements within a single class have varying heights based on the size of their text content. To address this, I need to increase the height of all these elements by 20px upon page load.

var visibleposts = document.getElementsByClassName("post-contain");
   for(var i =0; i <= visibleposts.length; i++){
     visibleposts[i].style.height = visibleposts[i].offsetHeight + 20 + "px";
   }

The above code snippet is what I implemented. It is wrapped inside an init() function that is triggered on page load. However, I am uncertain about its effectiveness as it is running on a meteor server. The function call is placed within the body onload event like so:

<head>
  <script src="jquery-2.1.4.min.js"></script>
  <script src="main.js"></script>
</head>
<body onload="init();">
</body>

<template name="FullFeed">
  {{#each posts}}
<!--    <a href="whenisay://{{adjective}}/{{noun}}/{{user}}/{{likes}}/{{date}}/{{_id}}">-->
    <a href="UnLiked.png">
      <div class="post-contain">
        <div class="chant">When I say <span class="varline">{{adjective}}</span> you say <span class="varline">{{noun}}</span></div>
<!--
        <div class="author-box">
          <p>By {{user}}<span class="spacer"> - </span>
            <img class="heart" src="UnLiked.png" onclick="console.log('hello');"/>
          </p>
        </div>
-->
      </div>
    </a>
    <div class="author-box">
      <p>By {{user}}<span class="spacer"> - </span>
        <img class="heart" src="UnLiked.png" onclick="console.log('hello');"/>
      </p>
    </div>
  {{/each}}
</template>

If you wish to inspect and troubleshoot the code, you can visit the live deployment at

Answer №1

As mentioned by humble.rumble, your code is not functioning properly because when the body loads, there are no ".post-contain" divs created by the FullFeed template yet.

It is recommended to not immediately execute the code to modify the generated DOM in main.js, but to use the Template.myTemplate.onRendered callback registering function instead. However, it should be noted that Template.myTemplate.onRendered from Meteor does not wait for individual data to be loaded. There are various solutions available to attach a callback after all items have finished loading. Please refer to other StackOverflow questions for more information:

  • How to execute helper function after DOM is ready in meteor
  • Running a function AFTER a meteor template is updated
  • Callback when all Template items finished rendering in Meteor?
  • Meteor : wait until all templates are rendered

If none of these methods suit your needs, you can consider using MutationObserver instead. In this case, you would observe for added <a/> items in the <body/> and then locate the .post-contain elements:

new MutationObserver(function (mutations){
    mutations.forEach(function (mutation){
        $(mutation.addedNodes).each(function (){
            if (this.localName == "a")
                var myNewDiv = $(".post-contain",this)[0]
        });
    });
}).observe($("body")[0], {childList: true});

If the Template global variable is not available until the document has fully loaded, you can utilize JQuery's .ready( handler ) method.

You can also use jQuery to adjust the height. Consider using the .height( function ) method like this:

$(".post-contain").height(function (index, height) {
    return (height + 20); // Increase the height of all ".post-contain" divs
});

All these techniques combined result in the following implementation:

$(function(){
    new MutationObserver(function (mutations){
        mutations.forEach(function (mutation){
            $(mutation.addedNodes).each(function (){
                if (this.localName == "a")
                    $(".post-contain",this).height(function (index, height){
                        return (height + 20);
                    });
            });
        });
    }).observe($("body")[0], {childList: true});
});

This solution has been tested on a local Meteor setup.


On a side note, have you considered why you need to add height in this manner? Perhaps using CSS padding rather than adjusting the height dynamically might be a simpler approach without needing to handle additional events like .resize().

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

When clicking, the drop-down feature is malfunctioning as all the menus are dropping down simultaneously

I have been trying to implement a dropdown on click feature for my website, but it is not functioning as intended. () When I click on button 1, button 2 also drops down unexpectedly. This behavior is not desired. Below is the code snippet from the page: ...

I'm finding it difficult to grasp the concept of CSS positioning

I've been diving into the world of HTML/CSS and decided to challenge myself by converting a PSD file to HTML. Here's what I've been working on: So far, I've encountered an issue where there is some space between two of my divs, and I c ...

Expanding the capabilities of jQuery

I'm attempting to integrate new functionality into a website that utilizes jQuery (specifically, I am trying to enable the draggable feature with the use of live()). I came across some code that supposedly achieves this, but I'm encountering dif ...

Ways to get rid of the white horizontal line generated by bootstrap framework?

I'm currently working on a responsive navbar design and I want it to appear transparent over a background image. However, my front-end knowledge is limited as I've only been learning for a week. Can anyone advise me on how to remove the white bar ...

Customizing button widths in CSS for landscape and portrait orientations with Bootstrap styling

How can I make multiple buttons in a container have equal width and resize when in landscape mode or on a wider screen? My goal is to achieve the following: https://i.sstatic.net/J8opN.png https://i.sstatic.net/NZSjj.png However, when I switch back to ...

Unable to access the .env file in Vue.js when executing cross-env NODE_ENV=development webpack-dev-server --open --hot

I'm attempting to utilize an .env file for storing local variables, but I am encountering an issue where they appear as undefined when I try to log them. Here is a snippet from my .env file (located at the root of my project): VUE_APP_STRAPI_HOST=htt ...

What are the steps to create a dynamic navigation bar in React without encountering hydration issues?

My goal is to dynamically show or hide links based on user authorization. Here's my initial approach: const Navbar = () => { const { canDo, ...} = useUser(); //A Zustand store return ( <> <div> <ul> ...

Applying a blur effect using CSS to all divs underneath

I have multiple divs and would like to apply a blur effect to all of them simultaneously. However, currently only the first div with the blur effect class is affected by the blur. When I click the button, I want the text "hello world" to become blurred. U ...

Whenever I select a different option such as "desi food", it automatically activates my order button

When I click on any other button like Desi Food, Fast Food, or Drinks, my order button is clicked automatically. I don't know if the buttons are overlapping each other or what the problem is. I am a beginner at this. <form method="post" action="o ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

What is the importance of context in the subscription method of RxJS or Angular Observables?

In the given situations, I am providing a child Component with a property that is updated later through an RxJs Observable subscription. Angular fails to detect changes when not using an anonymous function or binding the this context. // Situation 1 // C ...

Scrolling in Bootstrap 4 Cards conceals the fixed Header

Here's some HTML code featuring Bootstrap 4 elements. It showcases a fixed Header and Footer with scrollable Bootstrap Cards in between. When scrolling, the Headers may be hidden by the Cards. How can you adjust the layout so that the Cards scroll "be ...

How to make an HTML element draggable without the need for an ID

I am currently working on making dynamically created divs draggable. While I have successfully achieved this with pre-existing div elements as shown below: <div> This can be dragged around, but outputs cannot?! </div> the issue arises when ...

Can JavaScript be used to save data to a file on a disk?

As a beginner to intermediate programmer exploring AJAX, I was intrigued while learning about JavaScript. It caught my attention that many examples I have come across incorporate PHP for this task. While some may say 'I'm going about it the wrong ...

How to pause a loop temporarily before proceeding with the next iteration

I am facing a challenge where I want to trigger two events simultaneously, but only one event should be allowed to continue at a time. If an event is already in progress, I need the ability to forcefully stop it and allow the other event to take control. S ...

What is the best way to include a final tag on its own line?

I'm trying to add a new line for "Payment Remaining", but it doesn't go to the next line as expected. I need the final text to be on a separate line, Payment Remaining #authorization-wizard-start-work .btn-group label.active { color: #009 ...

ReactJS Error: Cannot find reference to 'require'

I'm currently implementing the DRY concept in React JS by attempting to reuse the same HTML partial across different files. Here is the partial: var AdminMenu = React.createClass({ getInitialState: function() { return {}; }, render: function() ...

Attempting to transform Go Pro GYRO data into rotational values using Three.js

I am currently working on converting gyro data from Go Pro to Three.js coordinates in order to project the footage onto the inside of a sphere. My goal is to rotate the sphere and achieve 3D stabilization. https://i.sstatic.net/VYHV6.png The camera' ...

How about this: "Can you turn a picture into text with just one click?"

Seeking assistance to enhance the 'About Us' page on our website. Each team member has a profile with their email address listed below, but we want to add a picture that disappears when clicked, revealing the email address in its place. You can ...

The image on Bootstrap isn't showing up

Can someone please help me troubleshoot why my logo image is not showing up? I can't figure out why the min and max width/height parameters are not working as intended. Here is my HTML: <div class="container-fluid"> <div class="head"> ...