How to Listen for Seek Event in Howler.js

This article provides a quick guide on how to listen for the seek event in Howler.js, a popular JavaScript audio library. You will learn the exact syntax required to detect when an audio track’s playback position is changed, using both instantiation configurations and dynamic event listeners, complete with clean code examples.

To listen for a seek event in Howler.js, you can use either the onseek callback property during the initialization of your Howl object, or the dynamic .on() method after creation. The seek event fires immediately after the playback position of the audio has been successfully changed using the .seek() method.

Method 1: Using the .on() Event Listener

The most flexible way to listen for the seek event is by registering a listener on your Howl instance using the .on('seek', callback) method.

// Initialize the sound
const sound = new Howl({
  src: ['track.mp3']
});

// Listen for the seek event
sound.on('seek', function(soundId) {
  console.log('The playback position has changed!');
  // Retrieve the new current position in seconds
  const currentPosition = sound.seek();
  console.log('New position: ' + currentPosition);
});

// Triggering a seek to 30 seconds (this will fire the event above)
sound.seek(30);

Method 2: Defining onseek During Initialization

If you want to set up the listener at the moment you create the audio object, you can pass the onseek function directly into the configuration object.

const sound = new Howl({
  src: ['track.mp3'],
  onseek: function() {
    console.log('Seek event detected during playback.');
  }
});

Key Behaviors to Keep in Mind