Dynamically adjust the height of the element and change the height on window resizing using jQuery

advertisements

I am working on a project where I need to set the height dynamically, means when the page loads the height must be set to itself and it's a responsive box, so when the browser window resizes the height increases but I am unable to fix it. I shared the script below. It's not something to calculate with window height or else, it should set and change the height based on window resizes. Any help?

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

var itemHeight = $('.item').height();
$('.item').each(function() {
  $(this).css({
    height: itemHeight + 'px'
  });
});

$(window).on('resize', function(event) {

  $('.item').each(function() {
    $(this).css({
      height: itemHeight + 'px'
    });
  });
});

Please see the jsfiddle: https://jsfiddle.net/rj1xy1ue/


I will suggest you to use % instead of px. px will fix the value, but % will automatically compute the values based on the available viewport.

var itemHeight = 20; //Sample value
$('.item').each(function () {
    $(this).css({
        height: itemHeight + '%'
    });
});

Simply, find the perfect value of itemHeight which is ideal for your case and then assign it. No need for extra resize event handler.

In your current code, in resize event you are assigning same value again which doesn't make any difference to the dimension. Hence you are not able to see the difference on resize.

Try this:

var itemHeight = $('.item').height();

function resizer() {
    $('.item').each(function () {
        $(this).css({
            height: itemHeight + 'px'
        });
    });
}
$(window).on('resize', function (event) {
    itemHeight = 350 //any different value
    resizer();
});

Sample Demo: http://jsfiddle.net/lotusgodkk/GCu2D/822/

Note: Make sure you change the value of itemHeight in resize handler