Reputation: 6852
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
Reputation:
The code you done is working like that:
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
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
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