1

Is there any way via jquery or javascript to make an element stretch its height to a certain set of numbers? I mean, as it accommodates more content, its height would only follow a pattern of numbers (multiples of a number).

Let's say in multiples of 100... a div's height as it extends taller would only be in this series -- 200px, 300px, 400px, etc. Hence, if it exceeds by just even 1 pixel off 200, it would automatically resize to 300.

It's hard to explain.

I need this because I made a vertically seamless pattern with torn edges and it would totally look perfect if it shows each tile completely.

I only know basic jquery and I don't have a bit of an idea on how to work this out.

My sincerest gratitude to whoever tends to my query!

Jawn
  • 41
  • 5

3 Answers3

1

something like:

$('element').css({ height : (0|(targetHeight + 99) / 100) * 100 });

if you want it automatic:

$(function(){
    var $elem = $('#element')
    $elem.css({ height : (0|($(elem).height() + 99) / 100) * 100 });
});
  • @cwolves What does `0|targetHeight` do? – Šime Vidas Jun 30 '11 at 18:22
  • @Šime Vidas - `Math.floor((targetHeight + 99) / 100)` –  Jun 30 '11 at 18:23
  • @cwolves `0|x` is equal to `Math.floor(x)`? – Šime Vidas Jun 30 '11 at 18:26
  • @Šime Vidas - yes, for all numbers < 2^31. `|` is a bitwise operator, all bitwise ops in JS have an implicit cast-to-int –  Jun 30 '11 at 18:27
  • `(5 | 9) === 13 // true` Pretty interesting stuff. – Robert Jun 30 '11 at 18:31
  • @Robert - bitwise math :) `(5).toString(2) == "101"` `(9).toString(2) == "1001"` `"101" | "1001" == "1101"` `parseInt("1101", 2) == 13`. It's actually much faster than other ways of doing the same thing. `0|` is effectively a "noop", FYI –  Jun 30 '11 at 18:36
1
var h = $('div').height();
$('div').height( Math.ceil(h/100) * 100 );
glortho
  • 13,120
  • 8
  • 49
  • 45
0

This function will take the current height and the unit number you want it to snap to, rounding to the nearest multipleOf.

function snapHeight(height, multipleOf) {
    return multipleOf * Math.round(height / multipleOf);
}

Examples:

snapHeight(930, 100); // returns 900
snapHeight(930, 50); // returns 950
$('#element').height(snapHeight($('#element').height(), 100)); // in jQuery
Matt King
  • 2,146
  • 15
  • 8