Varg
Varg

Reputation: 422

add delay to DOMMouseScroll event

I have some divs which should appear after user's scroll. So I track mouseScroll event. But I want to add some delay to my event. I tried to use setTimeout but it didn't help... If I do a full scroll of wheel (more than one per act), I get nothing except removing my class .shown. What should I do? Here is my code:

$(document).ready(function() {
  var timer;
  var delay = 1000;

  $(window).bind('mousewheel DOMMouseScroll', function(event) {
    var shown = $(".shown").removeClass('shown');
    timer = setTimeout(function() {
      if (event.originalEvent.wheelDelta > 14 || event.originalEvent.detail < 14) {
        // scroll up
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');
        } else {
          shown.siblings(":first").addClass('shown');
        }
      } else {
        // scroll down
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');

        } else {
          shown.siblings(":first").addClass('shown');
        }
      }
    }, delay);
  }, function() {
    clearTimeout(timer);
  });
});
.view {
  width: 300px;
  height: 20px;
  display: none;
  clear: both;
  transition: opacity 1s ease-out;
  opacity: 0;
}
#first {
  background: grey;
}
#second {
  background: red;
}
#third {
  background: blue;
}
#fourth {
  background: orange;
}
#fifth {
  background: green;
}
.view.shown {
  display: block;
  opacity: 1;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<div class="view shown" id="first"></div>
<div class="view" id="second"></div>
<div class="view" id="third"></div>
<div class="view" id="fourth"></div>
<div class="view" id="fifth"></div>

Unfortunately, I don't know, also, how to reverse this script with the same delay. Any help will be appreciated!

Upvotes: 1

Views: 292

Answers (1)

Dmitriy
Dmitriy

Reputation: 3765

try to use:

  $(window).bind('mousewheel DOMMouseScroll', function(event) {
    var shown = $(".shown").removeClass('shown');
    clearTimeout(timer);
    timer = setTimeout(function() {
      if (event.originalEvent.wheelDelta > 14 || event.originalEvent.detail < 14) {
        // scroll up
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');
        } else {
          shown.siblings(":first").addClass('shown');
        }
      } else {
        // scroll down
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');

        } else {
          shown.siblings(":first").addClass('shown');
        }
      }
    }, delay);
  });

Upvotes: 2

Related Questions