1

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>
Thibaud
  • 396
  • 5
  • 23

2 Answers2

3

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>
Community
  • 1
  • 1
DaniP
  • 37,813
  • 8
  • 65
  • 74
1

This syntax doesn't work:

if (value === other value, function() {

});

The correct syntax for an if statement is as follows:

if (value === other value) {
    // execute code in here
}

Also, you've got this:

$('scroll') === 1

Here, $('scroll') is a jQuery function that selects the <scroll> HTML element (which doesn't exist).

Instead, you can detect the page's scroll position in JavaScript using window.scrollY, which returns the number of pixels that the document is currently scrolled down from the top. For example:

if (window.scrollY < 100) {
    $('ul li:first-child').addClass('active');
} else if (window.scrollY < 200) {
    $('ul li:nth-child(2)').addClass('active');
}
jkdev
  • 11,360
  • 15
  • 54
  • 77
  • Thank you, but there is no possibilities to get each time the user scroll in the page ? not in pixel but just everytime he use his mousewheel? i think your solution can' t work if the body overflow is hidden – Thibaud Jun 28 '16 at 20:43
  • 1
    You can [add an event listener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) for the ["scroll" event](https://developer.mozilla.org/en-US/docs/Web/Events/scroll). – jkdev Jun 28 '16 at 20:48