javascripthtmljquery

How to get element's height and apply CSS to different elements based on height?


What I am trying to do is to get the heights of multiple elements with the same 'class'. If the element's height is over 400px I want it to set the height to the value it aquired minus 5px. And if it is under 400px I want it to do the same thing.

jQuery(document).ready(function( $ ){
  
  var cardHeight = $('.card').height();
  
  if (cardHeight > 400) {
    $(this).height(cardHeight - 5);
    }
  else{
    $(this).height(cardHeight - 5);
  }
  
}); 
.wrapper {
  width: 100%;
  overflow: hidden;
}
.wrapper .card {
  width: 20%;
  float: left;
  margin: 10px;
  background-color: red;
}
.wrapper .card:nth-child(1) {
  height: 333px;
}
.wrapper .card:nth-child(2) {
  height: 333px;
}
.wrapper .card:nth-child(3) {
  height: 500px;
}
.wrapper .card:nth-child(4) {
  height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<body>
<div class="wrapper">
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
</div>
</body>


Solution

  • In the original version of the code, the problem is in the moment when height() is taken immediately. The value of cardHeight = the height of the 1st element with the card class, you can verify this by setting the following value in the styles:

     &:nth-child(1) {
          height: 111px;
        }
        &:nth-child(2) {
          height: 222px;
        }
        &:nth-child(3) {
          height: 333px;
        }
        &:nth-child(4) {
          height: 444px;
        }
    

    cardHeight will be equal to 111px in this case.

    If you need to go through several elements with the same classes, you can use each. And then do the necessary manipulations with each element.

    jQuery(document).ready(function($) {
      $('.card').each(function(index, element) {
        var cardHeight = $(element).height();
        console.log(cardHeight);
    
        if (cardHeight > 400) {
          $(element).height(cardHeight - 5);
        } else {
          $(element).height(cardHeight - 5);
        }
      });
    });
    

    The if/else conditions themselves are redundant in this case.

    jQuery(document).ready(function($) {
      $('.card').each(function(index, element) {
        var cardHeight = $(element).height();
        console.log(cardHeight);
    
        $(element).height(cardHeight - 5);
      });
    });