I have two buttons, one that makes divs (of varying sizes) larger by a factor of 10 and one that makes them smaller by a factor of 10. After two clicks of the button that makes them smaller, the div is rounded to zero. No matter how many times you click the button that makes it larger it won't get larger because its multiplying the zero value. What is the standard way to fix this? This is necessary because in my application some of the divs are much much bigger than others, so while one div will be less than a pixel wide (and would then rightfully be invisible) others will be thousands of pixels wide.
UPDATE: My divs are actually circles representing planet diameters. I need these to be exact! If I click the smaller button 5 times, I want to be able to click the larger button 5 times and have it return to the exact diameter it was initially.
Also, it is probably not necessary to be able to make the divs smaller or larger an infinite number of times. What is the standard way to put a limit on it? Refer to my jsfiddle for an example of what I am trying to achieve. http://jsfiddle.net/dfjosh/vtxeD/12/
HTML
<a href="javascript:;" class="smaller">smaller</a>
<a href="javascript:;" class="larger">larger</a>
<div></div>
CSS
div {
width: 50px;
height: 50px;
background: cornflowerblue;
}
JavaScript
$('a').click(function() {
if($(this).hasClass('smaller')) {
var element = $('div');
element.animate({
'width' : element.width() * 0.1,
'height' : element.height() * 0.1
});
} else if($(this).hasClass('larger')) {
var element = $('div');
element.animate({
'width' : element.width() * 10,
'height' : element.height() * 10
});
}
});
Given that 0 evaluates as 'falsey' (or false-ish), you can use an || operator to pass 1 in the event that the width() or height() returns 0:
var element = $('div');
element.animate({
'width' : (element.width() || 1) * 10,
'height' : (element.height() || 1) * 10
});
JS Fiddle demo.
It seems to me that the problem isn't so much the divs going to zero as getting them to come away from it again.
That's easily done:
'width' : (element.width() * 10) || 1
How that works: If element.width() returns 0, of course 0 * 10 is also 0. 0 is a falsey value, so the || uses 1 instead.
Or if you prefer:
'width' : (element.width() || 1) * 10
...which just kicks in more quickly. :-)
More: JavaScript's Curiously Powerful OR Operator (||)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With