Rafhael
Rafhael

Reputation: 5

Dynamic Width = Height with jQuery

I searched all over the internet for hours but have not found the solution to this little problem I'm facing: Make a little script to keep DYNAMIC height relative to width.

I can do this using functions, but these functions are only limited to classes and so on, I have a dynamic form with $(this), but I want load the function individually for each div with the class or data.

My HTML example:

<section>
    <div>
        <figure data-image="height80">
            <img src="[MYIMG]" alt="Image" />
        </figure>
    </div>
</section>
<section>
    <div class="large">
        <figure data-image="height80">
            <img src="[MYIMG]" alt="Image" />
        </figure>
    </div>
</section>

My JS (with data):

height80();
$(window).resize(function() {
    height80();
});

function height80() {
  var photo80 = $('[data-image="height80"]');
  var photo80W = photo80.width() * 0.8;
    photo80.css({ 'height': photo80W, 'max-height': photo80W });
}

With this one I'll need to create a function for each diferent div size, so: there's a way to create a full funcional optimizated function to do this?

PS: I've tried to use $(this) but it return the body's width... =(

Thanks!

#FIDDLE HERE#

Upvotes: 0

Views: 110

Answers (2)

Ori Refael
Ori Refael

Reputation: 3018

No no no...use jQuery.call. This transfers the scope to this other function. Im using my Nexus atm so i can't give you a link. Then, in the funcation you may use $(this) and it will be dynamic to all elements called by this funcation.

Upvotes: 0

Adam Tal
Adam Tal

Reputation: 5961

I think your problem is the scope your accessing this.

Try updating your height80 function to this:

function height80() {
    $('[data-image="height80"]').each(function () {
        var width80 = $(this).width()*0.8;
        $(this).css({ 'height': width80, 'max-height': width80 });
    });
}

Here's an updated fiddle:

http://jsfiddle.net/Da9HT/

Upvotes: 1

Related Questions