Resize Height of elements when Resize window

280
November 21, 2016, at 7:49 PM

I have a problem with jQuery. Can't figure out how to do this. I have multiple sections width different heights:

<section id="1" class="something" style="height:111px; background:red;">1</section>
<section id="2" class="something" style="height:222px; background:blue;">2</section>
<section id="3" class="something" style="height:333px; background:green;">3</section>

My jQuery scales the height of each section when the window is smaller than 500px:

var org_height = $('.something').height();
$(window).resize(function() {
    $(".something").each(function() {
        var win = $(window).width();
        var height = $('.something').height();
        if(win < 500) {
            y = 500 - win;
            $('.something').css("height",org_height-y/3+"px");
        }
        else {
            $('.something').css("height",org_height+"px");
        }
    });   
});

JSFiddle: https://jsfiddle.net/owtz31jj/

How can I store the original height of each section and scale them depending on each height and back to the original height again. I greatly appreciate any help.

Answer 1

You can use jQuey.fn.data:

// Store original height for each .something
$(".something").each(function() {
    $(this).data('org_height', $(this).height());
});
$(window).on('resize', function() {
    var win = $(window).width();
    $(".something").each(function() {
        // Get the value storred in org_height using jQuery.fn.data
        var org_height = $(this).data('org_height'); 
        if(win < 500) {
            var y = 500 - win;
            $(this).css("height", org_height - y/3);
        }
        else {
            $(this).css("height", org_height);
        }
    });   
});
READ ALSO
$.fieldValue is not a function alert on login form submit

$.fieldValue is not a function alert on login form submit

In D7, with Devel, CTools and Ajax Login/Register plugins, I get an alert on submitting the login form on: http://p262957. mittwaldserver.

279
How can I initialize a new object inside a construction function so that each of its function can reuse it?

How can I initialize a new object inside a construction function so that each of its function can reuse it?

But when I do the above, it wont work. The whole purpose of initializing the object on top is the so that I don't have to recreate the same object in each function(xFunction1 and xFunction2).

164
if / else in jquery animation not working

if / else in jquery animation not working

I'm trying to use an if statement in jQuery to animate a div and all that's inside of it. I'm using code that's worked in other instances.

318