Tiaw Tiaw - 5 months ago 10
jQuery Question

can't use scroll function correctly after click

I made a function that increment class on a

li
list everytime i scroll on the page, so now i want to make the function on click but there is a conflict, for example if i click and i want to scroll again the increment function stop, how can i fix it ?



var scrollable = $('ul li').length - 1,
count = 0,
allowTransition = true;
$('body').bind('mousewheel', function(e) {

if (allowTransition) {
allowTransition=false;
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;
}

}
setTimeout(function() {
allowTransition=true;
}, 1000);
}
});

$('ul li').on('click', function() {
$('ul li').removeClass('active');
$(this).addClass('active');
});

body{
overflow:hidden;
}

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

here is a working script http://codepen.io/mozzi/pen/oLWZjY

you needed to reset allowTransition flag andd update the current count

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

    }
    setTimeout(function() {
      allowTransition=true;
    }, 1000);
  }
});

$('ul li').on('click', function() {
  $('ul li').removeClass('active');
  $(this).addClass('active');
  count = $(this).attr('count');
  allowTransition=true;
});
body{
  overflow:hidden;
  }

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" count='0'></li>
      <li count='1'></li>
      <li count='2'></li>
      <li count='3'></li>
    </ul>

Comments