Tiaw Tiaw - 5 months ago 34
Javascript Question

Get each scroll and increment active class

I want to make a custom slider on mousewheel event, my question is how can i do for get each scroll done on my page and add an active class on my 'ul li' and increment it one by one like:



if ($('scroll') === 1, function() {
$('ul li:first-child').addClass('active');
});
if ($('scroll') === 2, function() {
$('ul li:nth-child(2)').addClass('active');
});

ul li{
height:20px;
width:20px;
background:blue;
margin:5px;
list-style:none
}

ul li.active{
background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>




Answer

Based on this answer: , you can do something like this:

var scrollable = $('ul li').length - 1,
  count = 0;
$('body').bind('mousewheel', function(e) {
  if (e.originalEvent.wheelDelta / 120 > 0) {
    if (scrollable >= count && count > 0) {
      $('.active').removeClass('active').prev().addClass('active');
      count--
    } else {
      return false;
    }
  } else {
    if (scrollable > count) {
      $('.active').removeClass('active').next().addClass('active');
      count++
    } else {
      return false;
    }

  }
})
ul li {
  height: 20px;
  width: 20px;
  background: blue;
  margin: 5px;
  list-style: none
}
ul li.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="active"></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

Comments