Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery click function change between 3 classes. Why not working?

I have a code in javascript (w jquery) where the icon when clicked should change between 3 icons from volume up to down to off and again up down off, im thinking and resarching about this but none of things i try to work out seem to work please help. (the code is in $(document).ready).

var sound = 0;
  $('.sound').click(function(){
    var sound = sound + 1;
    if(sound == 1) {
      $('.sound').removeClass('glyphicon-volume-up');
      $('.sound').addClass('glyphicon-volume-down');
    } else if (sound == 2) {
      $('.sound').removeClass('glyphicon-volume-down');
      $('.sound').addClass('glyphicon-volume-off');
    } else if (sound == 3) {
      $('.sound').removeClass('glyphicon-volume-off');
      $('.sound').addClass('glyphicon-volume-up');
      var sound = 0;
    }
  });
like image 688
Adam Migacz Avatar asked Feb 19 '26 09:02

Adam Migacz


1 Answers

You can do something simple like this using an array

var sound = 0,
  cla = ['glyphicon-volume-up', 'glyphicon-volume-down', 'glyphicon-volume-off'];
$('.sound').click(function() {
  $(this).removeClass(cla[sound % 3])
    .addClass(cla[++sound % 3]);
  sound = sound % 3;
});
.glyphicon-volume-up {
  color: red;
}
.glyphicon-volume-down {
  color: green;
}
.glyphicon-volume-off {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="sound glyphicon-volume-up">Button</div>
like image 101
Pranav C Balan Avatar answered Feb 20 '26 22:02

Pranav C Balan