serge
serge

Reputation: 15239

OnLoad on an element

Suppose, as exercise, we have to dynamically adjust a div height to the one of the previous div.

My question is how to apply that on the "onload" of the element, in order to have each div's individul previous element...

Suppose the code

$(".description").css("height", 
                      $(".description").prev(".pic").height());
.pic {float: left; width: 50%; border: 1px solid red;}
.description {border: 1px dotted green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <figure>
    <div class="pic">pic1<br>this is a big pic</div>
    <div class="description">one is OK</div>
  </figure>
  <figure>
    <div class="pic">pic2<br>this<br> is a pic2<br>this is another big pic</div>
    <div class="description">two is NOK</div>
  </figure>
  <figure>
  etc...
  </figure>
</div>

you can see, the code works only for the first description, the second description is still adjusted to the first one.

PS.

Please do not propose to reformat the HTML, I am wondering how to apply some JS code for a specific HTML element: something like to have "onload" on a div element, to correctly identify the previous element.

Upvotes: 0

Views: 83

Answers (2)

Pointy
Pointy

Reputation: 413757

You can take advantage of the fact that .css() can be passed a function:

$(".description").css("height", function() {
  var element = this; // current "description" element
  return $(element).prev(".pic").height() + "px";
});

The value of this inside the callback function will be, in turn, each element that matches the selector (".description").

Upvotes: 3

MaZoli
MaZoli

Reputation: 1533

This code will do, you need to iterate through all the .pics

$(document).ready(function() {
  $(".description").each(function(){
    var height = $(this).parent().find('.pic').height();
    $(this).css('height',height);
  })
});

Upvotes: 1

Related Questions