Skip to content
Advertisement

bind two events on click jquery

I want to create a simple user interaction with a single button to start and stop recording audio,like whatsapp. I’ve looked on stackoverflow to understand if I was wrong, as I know it’s not possible to bind on the same element two click events, so I’ve decided to test the code on codepen but it will not produce the expected result:

$('#audioBtn').on('click' ,function(e){
  e.preventDefault();
  if( $(this).hasClass('active') ){
    $(this).removeClass('active')
    .addClass('inactive');
    console.log('Recording stopped');
  }
});

$('#audioBtn').on('click' , function(e){
  e.preventDefault();
  if( $(this).hasClass('inactive') ){
    $(this).addClass('active')
    .removeClass('inactive');
    console.log('Recording start');
  }
});

What happening is that the two events are logged on console at the same time, but this is not what I want, I just want to use the same button to start and stop the recordings and change the icon while the user is recording the audio. Is there any way to do this?

Advertisement

Answer

I know it’s not possible to bind on the same element two click events

This is not the case, it’s entirely possible to bind multiple event handlers for the same event type to a single element. The problem in your case is because the two handlers are conflicting with each other; one sets the class and the other detects the class and removes it.

To fix this you need to use a single event handler which detects the state of the element and updates it based on that. In your case a simple else statement will work.

$('#audioBtn').on('click', function(e) {
  e.preventDefault();
  if ($(this).hasClass('active')) {
    $(this).removeClass('active').addClass('inactive');
    console.log('Recording stopped');
  } else {
    $(this).addClass('active').removeClass('inactive');
    console.log('Recording start');
  }
});

Taking that a step further, you can use toggleClass() to swap the classes:

$('#audioBtn').on('click', function(e) {
  e.preventDefault();
  
  if ($(this).hasClass('active')) {
    console.log('Recording stopped');
  } else {
    console.log('Recording start');
  }
  
  $(this).toggleClass('active inactive');
});
.active {
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="audioBtn">Start/Stop</button>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement