Is this JavaScript code accurately matching the height of all three elements?

What I aim to achieve

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

I attempted to create a condition-like statement:

[ Comparing the heights of the 3 elements ]
→ When all are smaller than the height of content:

  • Stretches to the full height of content.
    (justify-content: space-between; or margin: auto;)

→ When it's greater than the content height:
ㅤ→ If the .middle element is the tallest among the 3:

  • Stretch the other 2 elements (.left and .right) to the full height of the content.

ㅤ→ Otherwise:

  • Compare the heights of the 2 elements other than .middle (.left and .right) and adjust the height of all (3 elements) to match the taller one.

By the way, why implement in JS instead of CSS:

I am already using flexbox.
However, when using swiper, I encountered two issues where ① the element from the previous slide moves to the next slide when the browser width/height changes & ② it cannot determine the correct height.
Therefore, I concluded that using JavaScript is necessary to "specify" the slide height and integrate it into swiper.


My current code

FullscreenFiddle / JSFiddle

jQuery

function maxHeight() {
  var maxH = 0;
  var contentH = 'calc(100vh - 79px)';
  $(".left, .middle, .right").each(function() {
    if ($(this).height() <= contentH) {
      $(".left, .right").css('justify-content', 'space-between');
      $(".middle").css('height', '100%');
    } else {
      if ($(".middle").height() > $(".left, .right").height()) {
        $(".left, .right").css({
          'height':'calc(' + contentH + ' - 100px)',
          'justify-content':'space-between'
      });
        $(".middle").css('height',contentH);
      } else {
        maxH = $(".left, .right").height();
        $(".left, .middle, .right").height(maxH);
      }
    }
  });
}
mySwiper.height = maxHeight();

Does this code accurately represent what I have described?

▼ Code only (The code snippet results may not look correct due to missing reset css)

/* The height alignment starts below this. */
/* swiper */
var mySwiper = new Swiper('.swiper-container', {
  direction: 'vertical',
  pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
    clickable: 'true',
  },
  keyboard: {
    enabled: true,
  },
  mousewheel: {
    forceToAxis: true,
    invert: true,
  },
  renderBullet: function(index, className) {
    return '<span class="' + className + '">' + (index + 1) + '</span>';
  },
});

console.log(mySwiper.height);


/* height alignment */
function maxHeight() {
  var maxh = 0;
  var conh = 'calc(100vh - 79px)';
  $(".left, .middle, .right").each(function() {
    if ($(this).height() <= conh) {
      $(".left, .right").css('justify-content', 'space-between');
      $(".middle").css('height', '100%');
    } else {
      if ($(".middle").height() > $(".left, .right").height()) {
        $(".left, .right").css({
          'height': 'calc(' + conh + ' - 100px)',
          'justify-content': 'space-between'
        });
        $(".middle").css('height', conh);
      } else {
        maxh = $(".left, .right").height();
        $(".left, .middle, .right").height(maxh);
      }
    }
  });
}

mySwiper.height = maxHeight();
/* The content follows from this point. */
/* CSS code example */
body {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  background-color: lightblue;
  padding: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css" rel="stylesheet"/>

<!-- The content continues below. -->
<div class="container">
  <p>This is a sample container.</p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/js/swiper.min.js"></script>

Answer №1

Have you considered using the matchHeight script? https://github.com/liabru/jquery-match-height

You could implement it like this:

<div data-mh="myheight"></>
<div data-mh="myheight"></>
<div data-mh="myheight"></>

Alternatively, in a JavaScript file:

$(function() {
    $('.item').matchHeight(options);
});

Answer №2

To achieve your desired outcome, JavaScript is not necessary. Let's review your requirements:

Compare the height of the 3 elements
→ If all are smaller than the content height:
  Stretch to full height of the content.

Outcome 1: All 3 elements have the same height as the content.

 → If greater than content height:
   → If .middle element is the tallest among the 3:
     Stretch other 2 elements (.left and .right) to full content height.

Outcome 2: All 3 elements with the same height as the content.

→ Otherwise:
  Compare heights of 2 elements besides .middle (.left and .right) and 
  adjust height of all (3 elements) to the taller one.

Outcome 3: All 3 elements share the same height as the content. Keep in mind that all elements are children of <div>.

Simply set all elements to match the parent div's size (content) and ensure that minimum content height equals window vh (vertical height). This can be accomplished with CSS alone.

The main challenge in your query is removing irrelevant code for this specific issue.

.wrap {
  width: 100%;
  height: 100%;
}

#content {
  position: relative;
  width: 100%;
  min-height: 100vh;
  border-radius: 5px;
}

.swiper-container, 
.swiper-wrapper,
.swiper-slide {
  min-height: 100vh;
}

.swiper-wrapper {
  justify-content: space-between;
}

.swiper-slide {
  align-items: center;
}

#abme,
#abmm,
#abee {
  min-height: 100vh;
  display: flex;
}
.middle,
.left,
.right {
  border: 1px solid red;
  margin: 1rem 0;
}

.left,
.right {
  display: flex;
  flex-direction: column;
}

/* left */

.left {
  padding: 0 0 0 0.6rem;
  width: 33.5rem;
}

.data {
  padding-top: 1.7rem;
  padding-bottom: 1.7rem;
}

.skill li {
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
}

.skill li:last-child {
  margin-right: 0;
}

.code {
  margin-top: 1.7rem;
}
figure {
  display: grid;
  grid-template: 'meter' auto 'name' min-content / 4.4rem;
  grid-row-gap: 0.5rem;
  margin-right: .9rem;
  font-size: 1rem;
}
figure img {
  grid-area: meter;
  align-self: center;
  justify-self: center;
}
figure .meter {
  width: 100%;
}
figure .meter-t {
  width: 50%;
  height: 50%;
}
figure figcaption {
  justify-self: center;
  min-width: 0;
}
.hobby>.data {
  padding-bottom: 0;
}

/* middle */
.middle {
  width: 55.2rem;
  flex-grow: 1;
  text-align: center;
  margin-left: 1rem;
  margin-right: 1rem;
}
.middle img {
  flex: 0 1 auto;
  margin: auto;
}
.middle p {
  float: none
}

/* right */
.right {
  padding: 0 0.6rem 0 0;
  width: 31.1rem;
}
.attributes>p:last-child {
  padding-top: 0;
}
<!-- from this -->
<div class="wrap">
  <div id="content">
    <div class="swiper-container">
      <div class="swiper-wrapper">
        <!-- page 1 -->
        <div class="swiper-slide">
          <div id="abme">
            <div class="left">
              <section class="name">
                <p class="title">Title</p>
                <p class="data" contentEditable>Content editable</p>
              </section>
            </div>

            <div class="middle">
              <p><img class="aboutImage" src="https://placehold.jp/0352ab/0352ab/400x200.png" alt="me" width="411" /></p>
              <p contentEditable>Content editable</p>
            </div>

            <div class="right">
              <section class="attributes">
                <p class="title">Title</p>
                <p class="data" contentEditable>Content editable</p>
              </section>
            </div>

          </div>
        </div>
        <!-- /page1 -->


      </div>
      <!-- /swiper-wrapper -->
    </div>
    <!-- /swiper-container -->
  </div>
  <!-- /content -->
</div>
<!-- /wrap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

AmazingStew 4 - How to substitute anchor element with its text

My document contains HTML content and I am looking to replace all anchor tags with their respective texts using BeautifulSoup. Here is the input: html = '''They are also much more fuel-efficient than <a href="http://someurl.com">rock ...

Is it possible to save the location of a draggable box using CSS3?

I'm trying to figure out how to store the position of a box in a fluid sortable row. Essentially, I want the position to be remembered when a user drags a box from category 1 to category 2, even after refreshing the page. Below is the HTML code for t ...

Obtain Data from a Table by Clicking a Button with jQuery

In the code snippet below, a table displays date time strings and a Close button. Upon clicking the close button, the respective row is removed; however, before removal, I would like to store the date in a variable. $(document).on('click', &ap ...

Using the section :export in the SCSS :root declaration

In the file test.module.scss, I store all my variables for colors, typography, and more. I want to be able to use these variables in my react components. However, the file starts with :root to define the variables: :root{ --color-white: #fff; --color-b ...

The close() function in the Fancybox success callback is not functioning properly when used with ajax

Code Snippet for index.php jQuery(function ($) { $("a.edit").fancybox(); }); <a class="edit" href="showForm.php?id=<?=$row['id']?>"> Edit </a> Code Snippet for showForm.php $id = $_GET['id']; jQuery(fu ...

I am having trouble authorizing a GET request with fetch

I've been attempting to utilize fetch in the browser, but it's not cooperating. Here's what I tried: fetch('https://api-2sizcg3ipa-uc.a.run.app/fats', { headers: {'Authorization': 'Basic ' + btoa('username ...

Creating dynamic button animations with Bootstrap 4 without impacting neighboring rows

I'm facing an issue with adding a simple animation to a button in one row of my webpage. When I change the margin-top of the button, all the rows below it also move along with the button. I tried using position-absolute on the button and position-rela ...

[php][html] stuck on trying to solve this error

Any help in figuring out the error on line 37 would be greatly appreciated. I've tried moving the ""; after echo and putting the entire PHP code in an img class="profilePic" src="http://i.imgur.com/ZICYW5z.png"/> and then using echo for the name (I ...

Code running successfully in Chrome's console, but encountering issues when executed on the webpage

Having some trouble assigning a function to a button in JavaScript. This is the button I'm working with, and my main goal right now is to make it responsive. <button id="artbtn" class="artbtn btn">Art</button> I experimented with this in ...

Determining the size of <li> elements within Bootstrap 4's tab-content feature

I need some assistance with this issue. I am attempting to calculate the length of a list using Bootstrap 4's tab-content feature. However, when the tab is inactive upon page load, the length is showing as 0. Even after opening the tab, it remains at ...

Utilizing DataTable in Angular 2: A Step-by-Step Guide

I am struggling to implement the DataTable in my Angular 2 application. It seems like adding a script tag directly into templates is not supported in Angular 2. Can anyone guide me on how to make this work? I have a feeling that I need to make some adjustm ...

"Exploring the world of Rails development, mastering Popups with Ajax for seamless deletes

Currently, I am working on a Rails project that features a standard Rails delete link within a popup. The challenge I am facing is that there are multiple popups present on the page. To manage this, I have implemented a hide action attached to the body (on ...

Tips for styling jqgrid header columns with CSS

Currently, I am creating a table using jqgrid. One of my objectives is to modify the background color and text color of the header. In my attempts to achieve this, I am experimenting with applying a class to the header. How can I effectively implement th ...

Progressively load an AJAX (jQuery) request response without needing to wait for completion

I'm looking to create a form that will utilize jQuery to send a list of keywords to a PHP file. Depending on the size of the keyword list, this file could potentially take a while to load. My goal is to dynamically load the PHP response into a div or ...

What is the best way to restrict a link to only a specific div element and not a Bootstrap

My HTML conundrum involves a div styled with the class .win_box: This particular div is nested within a Bootstrap column, and the link associated with it extends throughout the entirety of said column. However, I want to restrict user access to this link ...

Implementing Dynamic Checkbox Selection using JavaScript

Could someone please assist me with this coding challenge? HTML <div id="toggle"> <ul> <li class="active"><input type="checkbox" id="test" value="2014" name="test" checked/> 2014</li> <div style="display:block;" id ...

Having trouble with the unresponsive sticky top-bar feature in Zurb Foundation 5?

According to the information provided on this website, it is recommended to enclose the top-bar navigation within a div element that has both the class "contain-to-grid" and "sticky". However, I have noticed that while the "contain-to-grid" class exists in ...

Having difficulty generating dynamic rows and tree dropdowns in AngularJS

Struggling to implement dynamic row functionality with Angular JS. The rows are working well, but I also need to incorporate a tree dropdown within each row. Unfortunately, clicking the "add row" button populates the same data in all rows. I have shared m ...

Retrieving geographical data in GeoJSON format using AJAX request and displaying it on a Leaflet

I'm completely new to Leaflet and I'm struggling with how to integrate markers from a MySQL database onto a Leaflet map. Can anyone guide me on how to accomplish this using PHP and AJAX? .....{"type":"FeatureCollection","features":[{"geometry":{ ...

Content within innerHTML not appearing on the screen

I'm facing an issue with displaying an error message when the user enters incorrect username or password. The message should pop up below the sign-in box, but it's not showing up for some reason. Can anyone help me figure out why? Here is my cod ...