jQuery toggleClass example

Toggle class name on click in jQuery

by joshmoto

HTML

<audio controls>
  <source src="https://dev.joshmoto.wtf/mp3/crane-flock-aproaching.mp3" type="audio/mpeg">
</audio>

<div class="progress-bar">
  <div class="progress"></div>
</div>

CSS

HTML {
  height: 100%;
  min-height: 100%;
}

BODY {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
  height: 100%;
}

AUDIO {
  width: 100%;
  padding: 0;
  margin: 0 0 15px 0;
}

.progress-bar {
  position: relative;
  height: 15px;
  overflow: hidden;
  border-radius: .5rem;
  background: #fff;
}

.progress-bar .progress {
  display: block;
  height: 100%;
  width: 0;
  background: #2e71ff;
}

JavaScript

// window on load
$(window).on('load', function(e) {

  // once audio loaded get the audio object
  let aud = $('audio')[0];

  // on prorgess bar wrapper click
  $(document).on('click', '.progress-bar', function(e) {

    // get x position in progress bar
    let posX = e.pageX - $(this).offset().left;
    
    // create percentage 
    let percentage = parseInt((posX / $(this).outerWidth()) * 100);

    aud.currentTime = percentage / 100 * aud.duration;

    $('.progress',this).css('width', percentage + '%');

  });

});