Question: I want to show and hide a div based on where the user has scrolled to: so far I have: 

```
  $(document).scroll(function() {
    var y = $(this).scrollTop();
    if (y > 200) {
      $('.float-container').fadeIn();
    } else if (y > 300) {
      $('.float-container').fadeOut();
    }
  });

```

The button shows after 200 but needs to fadeout at 300, but it does not.

Any ideas?

Answer: 
The if statement will never hit the else if because if y=380, then it is still > 200. Try to swap the if and else if statements:

```
$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 300) {
    $('.float-container').fadeOut();
  } else if (y > 200) {
    $('.float-container').fadeIn();
  }
});

```

If you want it to only be visible between 200 and 300, do the following:

```
$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y >= 200 && y <= 300) {
    $('.float-container').fadeIn();
  } else {
    $('.float-container').fadeOut();
  }
});

```
Swap the order, since when >300 is true, the else if logic will not happen.

Also cache your selectors for performance with the frequent `scroll` event.

```
var $floatContainers = $('.float-container');
var $document = $(document).on('scroll', function() {
  var y = $document.scrollTop();

  if (y > 300) {
    $floatContainers.fadeOut();
  }
  else if (y > 200) {
    $floatContainers.fadeIn();
  }
});

```

Another option would be to nest the second conditional.

```
var $floatContainers = $('.float-container');
var $document = $(document).on('scroll', function() {
  var y = $document.scrollTop();

  if (y > 200) {
    if (y > 300) {
      $floatContainers.fadeOut();
    } else {
      $floatContainers.fadeIn();
    }
  }
});

```

If you want it to only be faded in for 201-300 scroll range...

```
var $floatContainers = $('.float-container');
var $document = $(document).on('scroll', function() {
  var y = $document.scrollTop();

  if (y > 200 && y <= 300) {
    $floatContainers.fadeIn();
  } else {
    $floatContainers.fadeOut();
  }
});

```