0

Hejsa!

I can't quite get this example to work.

http://aspitkbh.dk/lise/intro11/

The boxes are supposed to be the smallest possible width. (To not break the page while I wait for answer, I have set the width to auto there. Below is the code I thought would work.)

EDIT: I expect when the width is "too little", that the box will grow too high. Then I want to reduce the height until it is 170. The box will be too high or too wide because there's "too much" text in it.

<div class="myBoxExercise box1">Se en demo.
<button type="button" class="myButton" onclick="colorMe(this)">OK</button>
</div>
<div class="noMoreBox"></div>
<h3>Opgave 2</h3>
<div class="myBoxExercise box1">Du bliver.
<button type="button" class="myButton" onclick="colorMe(this)">OK</button>
</div>

.myBoxExercise {
    height: 170px;
    width: 100px;
    padding: 5px;
    float: left;
    margin: 5px;
    border-radius: 10px;
}


// JavaScript Document
// http://stackoverflow.com/questions/15227350/full-height-content-with-the-smallest-possible-width
$(document).ready(function() {
    $( "div.myBoxExercise" ).each(function( index ) {
        // The 160 = 170-2*5 is because you have to subtract the container padding and the element's own padding
        // Or not?
        while($(this).height() > 190) {
            currentWidth = $(this).width();
            $(this).width(currentWidth + 1);    
        }
        console.log( index + ": " + $( this ).width() );
    });
});
  • Your while loop looks to be never ending. – ZurabWeb Dec 19 '14 at 14:33
  • The while loop will never hit because $(this).height() is 170px as you set it in your CSS. 170 is not greater than 190. With that being said, I'm not entirely clear what you are trying to do. – NKD Dec 19 '14 at 14:44

2 Answers2

0

Found a way to solve it.

I changed the css to this:

.myBoxExercise {
    width: 50px;
    padding: 5px;
    float: left;
    margin: 5px;
    border-radius: 10px;
}

And ended with this js:

$( "div.myBoxExercise" ).each(function( index ) {
    while($(this).height() > 170) {
        currentWidth = $(this).width();
        $(this).width(currentWidth + 1);    
    }
    $(this).height(170);
    if ($(this).width() < 150) {
        $(this).width(150);
    }
});

It works pretty much how I wanted it to now. The comments helped me. Thanks.

0

If you are trying to that your div.myBoxExercise height should be not greater than 170 and its width should be not greater than 150... why not you are trying css max-height and max-width property.

 div.myBoxExercise{max-height:170px;max-width:150px;}

And if you are tying something else, please ignore this.

Shyam
  • 782
  • 5
  • 12