5

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?

Yukulélé
  • 15,644
  • 10
  • 70
  • 94
fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • How do you debug it? What lets you think than: `the last part where it checks if the number is less than 80 does not work`??? – A. Wolff Jan 22 '15 at 11:41

5 Answers5

30

This function check if number n is between a and b

function isBetween(n, a, b) {
   return (n - a) * (n - b) <= 0
}
Yukulélé
  • 15,644
  • 10
  • 70
  • 94
5

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);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
3

'' isn't a correct setting for the display property. From what you describe, you want to use block. Also, you don't need to use an each() loop here. Try this:

if (age >= 30 && age <= 80) {
    $('.display').css('display', 'block');
}

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

As I said in this post you can use a function similar to this one:

function between(n, a, b)
{
    return ((a==n)&&(b==n))? true : ($n-$a)*($n-$b)<0;
}

And it is not limited to integer numbers as other functions are.

Community
  • 1
  • 1
Luis Rosety
  • 396
  • 4
  • 10
-2

jQuery is weird.

In plain JavaScript:

this.style.display = "";

... will delete any display setting that has been made in JavaScript (or jQuery, or in raw HTML style="..." attribute), allowing the CSS-defined value (or default) to take over.

jQuery needs some kind of hack that I don't even remember right now to make it work... Not worth it IMO, when the JS is so simple.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592