I have a variable called 'age' and am trying to work out if it is between two numbers. In this case I want to find out if the age is between 30 and 80.
I have this so far...
if ( age >= 30 && age <=80 ) {
$('.display').each(function() {
$(this).css('display', '');
});
}
This works great if the age is below 30 then the .display div does not get displayed, but the last part where it checks if the number is less than 80 does not work.
Can anyone point me in the direction of a similar function I can read up on? Or am I doing something obvious wrong?
This function check if number n
is between a
and b
function isBetween(n, a, b) {
return (n - a) * (n - b) <= 0
}
The condition that you wrote to determine whether a value is in between two values is fine. What seems to be happening here is that once the condition of age >= 30
is reached, e.g. 31
, the display attribute gets updated, but once it goes over 80
, it doesn’t revert back any style changes.
Instead of modifying the display
CSS property, in jQuery you would typically use the show and hide methods, such as .toggle()
:
// only show if age is between 30 and 80
$('.display').toggle(age >= 30 && age <=80);
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