0
votes

So I am doing a drum machine project on Freecodecamp, where I am failing this condition.

" When I click on a .drum-pad element, the audio clip contained in its child element should be triggered. " So how do I trigger child element(in this case the audio element,to play the audio) while clicking or pressing the parent element?

I wrote something like this

class Drumset extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this)
  }
 handleClick(e){
   this.inputElement.click()
 }
 
  render() {
    return (
      <div>
        <div id="drum-machine" class="containerx box-middle">
          <div id="display">
            <div class="container">
              <div class="row">
                <div class="col">
                  <button type="button" class="drum-pad" id="Heater-1" onClick={this.handleClick}>
                    Q
                    <audio
                      class="clip"
                      id="Q"
          src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
                      type="audio/mpeg"
                    ></audio>

Well I tried putting the onClick event on inner element, which doesn't work either.

2
use this npmjs.com/package/use-sound , its super easy and dont need to make audio tag for playing sound files. - b3hr4d
thanks for the suggestion! - tanjim anim

2 Answers

0
votes

You can get your audio element by searching the DOM and then call .play() on it.

So your onClick handler becomes:

handleClick(e){
   const audio = document.getElementById("Q");
   audio.play();
}

If you have multiple buttons all with only 1 audio tag inside, you can use one general onClick handler and get the child audio element from the target of the event.

handleClick(e) {
    const audio = e.target.children[0];
    audio.play();
};
0
votes

Hello write write this in inner click function

//innerclick function 
Const Innerclick(e)=>{
e.stoppropagation()
// do the job here
}

Jsx code html here