[SOLVED] How to pass data from multiple function returns to single variable in js/jquery

Issue

I have a function, which gets paragraph height, and calculates image height by subtracting 100vh – paragraph height, every time image is loaded.

It results in not satisfying effect, I would like to substract the highest value that this function get.

So what I’m thinking the best approach would be to pass data from multiple loads to single variable, and pick the highest one. Although I’m js beginner and have no idea how to do that. Correct me if I’m wrong.

$(".module img").one("load", function () {
    
    var z = $(this).next('p').height()
    console.log(z)
    $('.module img').css({'height': 'calc(100vh - ' + z + 'px)'})

}).each(function() {
  if(this.complete) {
      //$(this).load(); // For jQuery < 3.0 
       $(this).trigger('load'); // For jQuery >= 3.0 
  }
});

Solution

Sth like this should do the job:

It’s simply storing highest value in variable and use it

let maxHeight = 0;

$(".module img").one("load", function () {
    
    var z = $(this).next('p').height()

    if (z > maxHeight){
      maxHeight = z;
    }

    console.log(z)
    $('.module img').css({'height': 'calc(100vh - ' + maxHeight + 'px)'})

}).each(function() {
  if(this.complete) {
      //$(this).load(); // For jQuery < 3.0 
       $(this).trigger('load'); // For jQuery >= 3.0 
  }
});

Answered By – Lukasz Piwowar

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.