Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Element visible betwen scroll points

I have some element that is visible when scroll is bigger than 890px. But i have problem that element has to be visible between 890px and 920px, and if user scroll more thna 920 or less than 890px i need to hide that element.

I am using animated css for adding animation to element when appear.

This is what i have for now in JS

var $document = $(document),
    $elementField = $('.center-field');

$document.scroll(function () {
    if ($document.scrollTop() >= 890) {
        $elementField.stop().addClass("show animated bounceInDown");  
    }
});

Now it will appear when user scroll more than 890px, but when user goes back it will stay again, is there somekind of watch user scroll?

Upvotes: 0

Views: 29

Answers (3)

user6377043
user6377043

Reputation:

The code you done is working like that:

  • every time you scroll:
  • check if the scroll is more than 890px
  • if so add the class

As you can see it doesn't contains the logic of hiding the element. You need to check if the scroll is less than 890px and remove the classes. You can try something like that (assuming that when you node hasn't the class show it is hidden):

var $document = $(document),
    $elementField = $('.center-field');

    $document.scroll(function () {
        var scroll = $document.scrollTop();

        if (scroll >= 890 && scroll <= 920) {
            $elementField.addClass("show animated bounceInDown").removeClass("fadeOut");  
        } else {
            $elementField.removeClass("show bounceInDown").addClass("fadeOut");  
        }
    });

Upvotes: 1

DavidDomain
DavidDomain

Reputation: 15293

Just be a bit more specific with the if condition.

var $document = $(document),
    $elementField = $('.center-field');

$document.scroll(function () {
  if ($document.scrollTop() >= 890 && $document.scrollTop() <= 920) {
    $elementField.css('color', 'tomato');  
  } else {
    $elementField.css('color', 'blue'); 
  }
});
body {
  position: relative;
  height:1800px;
}

.center-field {
  position: absolute;
  top: 900px;
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>scroll down please</p>
<h1 class="center-field">Hello</h1>

Upvotes: 1

Ricardo van Laarhoven
Ricardo van Laarhoven

Reputation: 788

Cant you do a hide in the else?

$document.scroll(function () {
if ($document.scrollTop() >= 890) {
    $elementField.stop().addClass("show animated bounceInDown");  
}else{
    $elementField.hide(); //or something like that
}

Upvotes: 0

Related Questions