JavaScript does not execute until a page refresh occurs

I've encountered an issue with my javascript snippet that usually creates divs of equal height, but now it only works after refreshing the page. Here's an example:

<div class="container">
  <div class="row text-center">

    <%= link_to "http://www.manlyartofbbq.com" do %>
      <div class="col-sm-6 col-md-4">
        <div class="site-preview-box">
          <h2>WIP: Manly Art of BBQ</h2>
          <h4>Branding, Logo Design, UI/UX Design, Web Development</h4>
          <%= image_tag 'portfolio_mab.png', class: "portfolio-image" %>
          <p><a href="www.manlyartofbbq.com">The Manly Art of BBQ</a> is a humorous website that gives information on a variety of "manly" topics.</p>
          <p><strong>This site has a vast array of user-submitted content sorted in a Reddit-like fashion, as well as a few online "tools" that were a lot of fun to develop.</strong></p>
        </div> <!-- site preview box -->
      </div> <!-- column box -->
    <% end %>

    <%= link_to "http://www.ocoutreach.com" do %>
      <div class="col-sm-6 col-md-4">
        <div class="site-preview-box">
          <h2>WIP: OC Outreach</h2>
          <h4>Branding, Logo Design, UI/UX Design, Web Development</h4>
          <%= image_tag 'portfolio_oco.png', class: "portfolio-image" %>
          <p><a href="www.ocoutreach.com">OC Outreach</a> is a non-profit community organization that operates in the Orange County area.</p>
          <p><strong>This was a fairly simple site functionality-wise, but it was cool to design every aspect of a site (logos, design, etc.) from the ground up.</strong></p>
        </div> <!-- site preview box -->
      </div> <!-- column box -->
    <% end %>


  </div> <!-- row -->

</div> <!-- page container -->


<script>
  $( document ).ready(function() {
      var heights = $(".site-preview-box").map(function() {
          return $(this).height();
      }).get(),
      maxHeight = Math.max.apply(null, heights);
      $(".site-preview-box").height(maxHeight);
      window.onresize = function(){ location.reload(); }
  });
</script>

Rather than getting uniform divs, I initially see this odd result:

https://i.sstatic.net/1vw7G.png

Only after refreshing does it finally display correctly like this:

https://i.sstatic.net/F248X.png

Any suggestions on how to make it work without having to refresh?

ADDITIONAL INFO I tried different approaches suggested elsewhere, such as changing load for ready, but they didn't solve my specific issue.

Answer №1

Ensure your divs only appear once all images have completed loading. When the page is reloaded, the divs display correctly because by then all the images are stored in the browser cache and the JavaScript can determine the appropriate size.

To achieve this in jQuery, modify your ready function to:

$(window).on("load", function() {
    // Add your custom logic here.
});

This should solve the issue. If not, consider using a method similar to the following example:

var img = new Image();
img.onload = function() { alert("Height: " + this.height); }
img.src = "http://path/to/image.jpg"

Answer №2

By setting a CSS width and height for images, you can ensure that they always appear as desired within boxes. In this particular scenario, the browser initially caches the images, causing them to display correctly upon subsequent loads due to retrieving them from the cache.

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

Tips on declaring an object with a nested array of objects in TypeScript

In my code, I have defined two classes. One is called Stuff and the other is called Thing. class Stuff { constructor() { } things: Thing[] = []; name: string; } class Thing { constructor() { } active: boolean; } As I was working on my applicat ...

Tips for subscribing to an Angular Unit Test:

In the process of writing test cases for a component, I first tackled a basic test case to ensure smooth functionality. Initially, I faced Dependency Injection errors and managed to resolve them. The current challenge I am encountering involves mocking API ...

Node.js routing issues leading to rendering failures

I have been working on a website that involves carpooling with drivers and passengers. When a driver submits their details, they are directed to a URL where they can select the passenger they want to ride with. Here is the code snippet I have written: ap ...

The combination of curly brackets and displaying items in a list

What is the reason behind React's failure to render the list items when the arrow function objectList contains curly braces? export default function StatelessList() { const objDev = [ { id: 1, surename: "John", name: "Wayne" ...

Is there a way to create a self-contained installation package for my Vue application?

Is it possible for my application to be downloaded and installed without requiring internet access after the download is complete? I am looking to create a standalone installer for this purpose. Are there any suggestions on how to go about implementing t ...

Interaction when a button is clicked repeatedly 10 times on a webpage

Looking for assistance in creating a website feature where clicking a link ten times opens another webpage. Any help would be greatly appreciated. Thank you in advance! ...

Discovering the method to access a getter from a different JavaScript file

In a laravel + vuejs project, I am trying to access my currentUser role in my Acces.js file using store.getters.currentUser but encountering an error: Error in render: "TypeError: Cannot read property 'getters' of undefined I have tried mu ...

JavaScript Invocation

Ajax is used to append data to a php page, functioning like a comment panel where clicking a button loads more comments when scrolled to the bottom. Here's the ajax function for loading more comments: $("#loadmorecomments").click(function(){ $(&apo ...

Utilizing CSS to position elements on a webpage

Currently, I am immersed in a CSS and HTML project aimed at honing my skills. The main challenge I face involves positioning a Google Maps image to the right of a paragraph. Despite several attempts, I have been unable to achieve the desired layout. Can an ...

maintaining a log of form data through session tracking

I have a form where users can input data to generate a badge. I am using sessions to store a history list for users, and if they select an element from the list, the data will automatically populate in the form. The issue I'm facing is that whenever I ...

In VB.Net, utilize regex to eliminate whitespace except for the content within <script> tags

I'm seeking a solution to minimize the size of my HTML output stream by eliminating empty lines and whitespace. I've attempted using regex, but my current pattern is inadvertently removing entire script blocks. How can I refine my approach to ens ...

Encountering an issue in Next.js when using getStaticProps: reading 'map' of undefined properties

The Image above shows the error and the code I have attempted.Server Error TypeError: Cannot read properties of undefined (reading 'map') This particular error occurred during the page generation process. Any console logs will appear in the term ...

What makes Twitter Bootstrap special that modal events function in JQuery but not in pure JavaScript?

When working with the Twitter Bootstrap modal dialog, there is a set of events that can be utilized with callbacks. For instance, in jQuery: $(modalID).on('hidden.bs.modal', function (e) { console.log("hidden.bs.modal"); }); I ...

Unable to trigger @click event on nuxt-link component within Nuxt 3

As per a Nuxt 2 question on Stack Overflow, it was suggested that the following code should prevent nuxt-link from navigating to a new page: <nuxt-link :to="`/meet`" class="group font-normal" @click.native="event => event.pre ...

When using JavaScript to style.display = "block", the Bootstrap-4 column layout may experience a display break

My div is initially displaying properly in one row at the beginning. However, when the user changes the select option to "b" and then back to "a," the display breaks. The two texts "my left side text" and "my right text" are displayed on two lines, one be ...

Reopen a jQuery dialog box already filled with content

Whenever I click a button, it loads an external page from the same domain into a div and displays that div as a jQuery UI dialog box. <div id="Dialog_box"></div> <script type="text/javascript"> $(function() { $("#Dialog_box" ...

Analyzing vast datasets from contrasting perspectives

Looking for a way to compare two different data storages that contain the same data. The data in question is: const object1 = { "name": "John", "age": "30", "height": "180 cm", "stand ...

Safari: Height of 100% not functioning as expected

Currently, I have a div with the class of "signup-login-forms" that is set to have a height of 40vh and span 100% of the browser width. Inside this div are two forms positioned next to each other. The goal is to have both forms fill the entire height of th ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Transfer a JSON object to a Java Class without relying on a servlet

I have a form in HTML where I collect user input and store it as an object in JavaScript. Here is how I am creating the object: var dataObject = { Name: getName(), Age : getAge() } Now, I want to send this object using Ajax to a b ...