Pregunta

I have the following jquery code to resize a set of elements so that they are all the same height of the tallest element. The function works fine when i refresh the screen, but the $(window).resize() doesn't seem to work.

jQuery(document).ready(function($) {

    function equal_height(target) {
        var maxHeight = -1;

        $(target).each(function() {
            maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
        });

        $(target).each(function() {
            $(this).height(maxHeight);
        }); 
    };

    var responsive_viewport = $(window).width();

    if (responsive_viewport >= 768) {

        equal_height('.cta-text');

        $(window).resize(function() {
            equal_height('.cta-text');
        });
    }

});
¿Fue útil?

Solución

Worked it out!

The problem isn't how or when the function is called, it's not working because it's basing the new size on the size that was set the first time the function was run.

I've added this to the start of the equal_height function, to reset the height of the element to it's natural height.

$(target).each(function() { 
    $(this).height('auto');
}); 

Otros consejos

I would consider refactoring to separate out your functions and events. Also you are checking the window on document ready, at which point the window object hasn't loaded anything yet (the DOM is ready before the the window renders). Try this:

jQuery(window).load(function($) {

    var responsive_viewport = $(window).width();

    if (responsive_viewport >= 768) {
        equal_height('.cta-text');

        $(window).resize(function() {
            equal_height('.cta-text');
        });
    }

});


function equal_height(target) {
    var maxHeight = -1;

    $(target).each(function() {
        maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
    });

    $(target).each(function() {
        $(this).height(maxHeight);
    }); 
};

I should also mention that because your resize function is within a conditional statement, it will only fire when the viewport is above 768 pixels — so make sure that you are taking that into account while debugging.

Use $(window).resize(function(){}); to trigger events on resize. It only works when you refresh because you're currently not telling it to run anything on resize, but rather when the document fully loads and is ready.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top