Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="root"></div>
              
            
!

CSS

              
                @import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@500&display=swap");

body {
  background-color: lightGray;
}

h1 {
  font-family: "IBM Plex Mono", monospace;
  text-align: center;
  font-size: 3em;
  /*these margins differ from original for better CodePen presentation*/
  margin-top: 0;
  margin-bottom: 5px;
}

#music-notes {
  font-size: 0.75em;
}

#drum-machine {
  margin: auto;
  background-color: black;
  height: 400px;
  width: 740px;
  position: relative;
  top: 0;
  bottom: 4em;
  border: 6px solid #00e600;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
/*CHANGED HERE FOR .DRUM-PAD AND DRUM-PAD:ACTIVE*/
.drum-pad {
  box-sizing: content-box;
  border-radius: 15px;
  font-size: 28px;
  background-color: gray;
  font-family: Courier New;
  font-weight: bold;
  cursor: pointer;
  border-bottom: solid 3px #505050;
  border-right: solid 3px #404040;
}

.drum-pad:active {
border: solid 1px black;
}

#button-container {
  background-color: darkGray;
  width: 280px;
  height: 280px;
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 10px;
  padding: 5px;
  border-radius: 15px;
}

#controls {
  height: 260px;
  width: 280px;
  background-color: darkGray;
  display: grid;
  grid-template-rows: 1fr 1fr 1fr 1fr;
  grid-gap: 7px;
  font-weight: bold;
  text-align: center;
  padding: 15px;
}

#power-button {
  border-radius: 50%;
  padding: 8px;
  background-color: black;
  font-size: 23px;
  float: right;
  cursor: pointer;
}

button.power-on {
  color: #0099ff;
  border: 2px solid gray;
}
button.power-off {
  color: white;
  border: 2px solid black;
}

#volume {
  padding: 15px;
}

#volume-switch-label {
  font-family: "IBM Plex Mono", monospace;
  font-size: 18px;
}

#display {
  background-color: gray;
  border: 2px solid black;
  display: inline-block;
  width: 80%;
  height: 67px;
  margin: 0 auto;
}
/*display text:*/
p {
  font-family: "IBM Plex Mono", monospace;
  font-size: 20px;
}
#bank {
  padding: 15px;
}

#bank-switch-holder {
  border: 2px solid black;
  background-color: black;
  display: inline-block;
  height: 20px;
  width: 50px;
  cursor: pointer;
  border-radius: 14px;
}

#bank-switch {
  cursor: pointer;
  display: block;
  background-color: red;
  height: 100%;
  width: 50%;
  border-radius: 10px;
}

.switched {
  position: relative;
  left: 50%;
}

@media only screen and (max-width: 750px) {
  
  body {
    display: flex;
    flex-direction: row;
    justify-content: center;
  }
  
  h1 {

    font-size: 2.5em;
    /*m-bottom is different from original for better CodePen presentation*/
    margin-bottom: -2.5em;
    margin-top: 0;
  }

  #drum-machine {
    top: 0.5em;
    bottom: 0;
    min-width: auto;
    min-height: auto;
    height: 700px;
    width: 400px;
    transform: scale(0.7);
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
  }

  #button-container {
    top: 0;
    left: 0;
    margin-top: 10%;
  }

  #controls {
    margin-bottom: 10%;
  }
}

@media only screen and (max-width: 280px){
  
  h1{
    font-size: 2em;
    margin-bottom: -3em
  }
  
  #drum-machine{
    padding: 0;
    height: min-content;
  }
  
  #button-container{
    margin: 15px;
  }
  
  #controls {
    margin: 0 5px 15px 5px;
    width: 16em;
  }
  
} 

              
            
!

JS

              
                import { FontAwesomeIcon } from "https://cdn.skypack.dev/@fortawesome/react-fontawesome";
import {
  faPowerOff,
  faMusic
} from "https://cdn.skypack.dev/@fortawesome/free-solid-svg-icons";

const { useRef, useState, useReducer, useContext, useEffect } = React;

const GlobalStateContext = React.createContext();
const DispatchContext = React.createContext();

/*custom hooks to export refs to Buttons & other components (these were used in desktop code editor. Probably unnecessary in CodePen)*/

function useAudioRef() {
  return useRef([]);
}

function useButtonRef() {
  return useRef([]);
}

const ACTIONS = {
  TOGGLE_POWER: "togglePower",
  CHANGE_VOLUME: "changeVolume",
  TOGGLE_BANK: "toggleBank",
  CHANGE_DISPLAY: "changeDisplay"
};

function MasterProvider({ children }) {
  const kit1 = {
    displayText: "Heater Kit",
    buttonList: [
      {
        letter: "Q",
        displayText: "Heater 1",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
      },
      {
        letter: "W",
        displayText: "Heater 2",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3"
      },
      {
        letter: "E",
        displayText: "Heater 3",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3"
      },
      {
        letter: "A",
        displayText: "Heater 4",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3"
      },
      {
        letter: "S",
        displayText: "Clap",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3"
      },
      {
        letter: "D",
        displayText: "Open Hi-Hat",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3"
      },
      {
        letter: "Z",
        displayText: "Kick n' Hat",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3"
      },
      {
        letter: "X",
        displayText: "Kick",
        url: "https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3"
      },
      {
        letter: "C",
        displayText: "Closed Hi-Hat",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3"
      }
    ]
  };

  const kit2 = {
    displayText: "Smooth Piano Kit",
    buttonList: [
      {
        letter: "Q",
        displayText: "Chord 1",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Chord_1.mp3"
      },
      {
        letter: "W",
        displayText: "Chord 2",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Chord_2.mp3"
      },
      {
        letter: "E",
        displayText: "Chord 3",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3"
      },
      {
        letter: "A",
        displayText: "Shaker",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Give_us_a_light.mp3"
      },
      {
        letter: "S",
        displayText: "Open Hi-Hat",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Dry_Ohh.mp3"
      },
      {
        letter: "D",
        displayText: "Closed Hi-Hat",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Bld_H1.mp3"
      },
      {
        letter: "Z",
        displayText: "Punchy Kick",
        url: "https://s3.amazonaws.com/freecodecamp/drums/punchy_kick_1.mp3"
      },
      {
        letter: "X",
        displayText: "Side Stick",
        url: "https://s3.amazonaws.com/freecodecamp/drums/side_stick_1.mp3"
      },
      {
        letter: "C",
        displayText: "Snare",
        url: "https://s3.amazonaws.com/freecodecamp/drums/Brk_Snr.mp3"
      }
    ]
  };

  const [state, dispatch] = useReducer(reducer, {
    isPowerOn: true,
    currentVolume: 0.5,
    kitOneIsActive: true,
    isPlaying: false,
    drumKitData: kit1,
    displayText: kit1.displayText
  });

  function reducer(state, action) {
    switch (action.type) {
      case ACTIONS.TOGGLE_POWER:
        return { ...state, isPowerOn: !state.isPowerOn };

      case ACTIONS.CHANGE_VOLUME:
        return { ...state, currentVolume: action.payload };

      case ACTIONS.TOGGLE_BANK:
        return {
          ...state,
          kitOneIsActive: !state.kitOneIsActive,
          drumKitData: state.kitOneIsActive === true ? kit2 : kit1,
          displayText:
            state.kitOneIsActive === true ? kit2.displayText : kit1.displayText
        };

      case ACTIONS.CHANGE_DISPLAY:
        return { ...state, displayText: action.payload };

      default:
        return state;
    }
  }

  return (
    <GlobalStateContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </GlobalStateContext.Provider>
  );
}

function App() {
  return (
    <MasterProvider>
      <div className="App">
        <h1>
          Drum Pad{" "}
          <sup>
            <FontAwesomeIcon
              icon={faMusic}
              id="music-notes"
              aria-hidden="true"
            />
          </sup>
        </h1>
        <Machine />
      </div>
    </MasterProvider>
  );
}

function Machine() {
  return (
    <div id="drum-machine">
      <Buttons />
      <Controls />
    </div>
  );
}

function Buttons() {
  const state = useContext(GlobalStateContext);
  const dispatch = useContext(DispatchContext);
  const buttonRef = useButtonRef();
  const audioRef = useAudioRef();
  const keyEventCodeRegex = /^(Key)[Q|W|E|A|S|D|Z|X|C]/;

  function buttonHover(e) {
    if (state.isPowerOn) {
      function showInstrument(index) {
        dispatch({
          type: ACTIONS.CHANGE_DISPLAY,
          payload: state.drumKitData.buttonList[index].displayText
        });
      }
      switch (e.target.id) {
        case "Q":
          showInstrument(0);
          break;
        case "W":
          showInstrument(1);
          break;
        case "E":
          showInstrument(2);
          break;
        case "A":
          showInstrument(3);
          break;
        case "S":
          showInstrument(4);
          break;
        case "D":
          showInstrument(5);
          break;
        case "Z":
          showInstrument(6);
          break;
        case "X":
          showInstrument(7);
          break;
        case "C":
          showInstrument(8);
          break;
        default:
          break;
      }
      return (e.target.style.backgroundColor = "rgb(0, 230, 0)");
    } else {
      return null;
    }
  }

  function buttonExit(e) {
    dispatch({
      type: ACTIONS.CHANGE_DISPLAY,
      payload: state.drumKitData.displayText
    });
    return (e.target.style.backgroundColor = "gray");
  }

  //Will make the sound stop if power is switched off
  useEffect(() => {
    var activeAudio = audioRef.current.filter((audio) => audio.ended === false);

    if (state.isPowerOn === false) {
      function stopSound(audio) {
        audio.pause();
        audio.currentTime = 0;
      }
      activeAudio.forEach((audio) => stopSound(audio));
    } else {
      return null;
    }

  }, [state.isPowerOn, audioRef]);

  //Will change volume dynamically as sound plays, & not just before playback
  useEffect(() => {
    audioRef.current.forEach((audio) => (audio.volume = state.currentVolume));
    //any cleanup necessary? Probably not
  }, [state.currentVolume, audioRef]);

  function handleAudioClick(e) {
   
    e.target.style.border = "solid 1px black";

    function clickAudio(refIndex) {
      dispatch({
        type: ACTIONS.CHANGE_DISPLAY,
        payload: state.drumKitData.buttonList[refIndex].displayText
      });
      audioRef.current[refIndex].play();

      //on another click
      if (!audioRef.current[refIndex].paused) {
        console.log("clicked again");
        audioRef.current[refIndex].currentTime = 0;
        audioRef.current[refIndex].play();
      }
    }
    
    if (state.isPowerOn) {
      const clickedSound = e.target.children[0].attributes[2].nodeValue;

      switch (clickedSound) {
        case audioRef.current[0].src:
          clickAudio(0);
          break;

        case audioRef.current[1].src:
          clickAudio(1);
          break;

        case audioRef.current[2].src:
          clickAudio(2);
          break;

        case audioRef.current[3].src:
          clickAudio(3);
          break;

        case audioRef.current[4].src:
          clickAudio(4);
          break;

        case audioRef.current[5].src:
          clickAudio(5);
          break;

        case audioRef.current[6].src:
          clickAudio(6);
          break;

        case audioRef.current[7].src:
          clickAudio(7);
          break;

        case audioRef.current[8].src:
          clickAudio(8);
          break;

        default:
          return null;
      }
    } else {
      console.log("power is off.");
    }
  }     
    
  const mouseUpReturnStyles = (index) => {
    
    let buttonStyle = buttonRef.current[index].style;
    buttonStyle.borderBottom = "solid 3px #505050";
    buttonStyle.borderRight = "solid 3px #404040";
    buttonStyle.borderTop = "solid 3px rgb(227, 227, 227)";
    buttonStyle.borderLeft = "solid 3px rgb(227, 227, 227)";
  };

  function handleAudioKeyDown(e) {
    function audioTap(refIndex) {
      if (state.isPowerOn === true) {
        dispatch({
          type: ACTIONS.CHANGE_DISPLAY,
          payload: state.drumKitData.buttonList[refIndex].displayText
        });
        buttonRef.current[refIndex].style.backgroundColor = "rgb(0, 230, 0)";
        buttonRef.current[refIndex].style.border = "solid 1px black";
        audioRef.current[refIndex].play();
        //on another tap of same key:
        if (
          !audioRef.current[refIndex].paused &&
          audioRef.current[refIndex].currentTime > 0
        ) {
          console.log("tapped again");
          audioRef.current[refIndex].pause();
          audioRef.current[refIndex].currentTime = 0;
          audioRef.current[refIndex].play();
        }
      } else if (state.isPowerOn === false) {
        buttonRef.current[refIndex].style.border = "solid 1px black";
      } else {
        return null;
      }
    }

    if (keyEventCodeRegex.test(e.code)) {
      switch (e.code) {
        case "KeyQ":
          audioTap(0);
          break;

        case "KeyW":
          audioTap(1);
          break;

        case "KeyE":
          audioTap(2);
          break;

        case "KeyA":
          audioTap(3);
          break;

        case "KeyS":
          audioTap(4);
          break;

        case "KeyD":
          audioTap(5);
          break;

        case "KeyZ":
          audioTap(6);
          break;
        case "KeyX":
          audioTap(7);
          break;

        case "KeyC":
          audioTap(8);
          break;

        default:
          return null;
      }
    } else {
      return null;
    }
  }

  useEffect(() => {
    //if(state.isPowerOn===true){
    window.addEventListener("keydown", handleAudioKeyDown);
    return () => {
      window.removeEventListener("keydown", handleAudioKeyDown);
    };
    /*all dependencies of this effect are the same state values used in the handleAudioKeyDown function above*/
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.isPowerOn, state.kitOneIsActive, state.drumKitData]);

  function makeButtonGray(e) {
   
    const returnStyles = (btnIndex) => {
      let buttonStyle = buttonRef.current[btnIndex].style;

      buttonStyle.backgroundColor = "gray";
      buttonStyle.borderBottom = "solid 3px #505050";
      buttonStyle.borderRight = "solid 3px #404040";
      buttonStyle.borderTop = "solid 3px rgb(227, 227, 227)";
      buttonStyle.borderLeft = "solid 3px rgb(227, 227, 227)";
    };

    if (keyEventCodeRegex.test(e.code)) {
      switch (e.code) {
        case "KeyQ":
          returnStyles(0);
          break;
        case "KeyW":
          returnStyles(1);
          break;
        case "KeyE":
          returnStyles(2);
          break;
        case "KeyA":
          returnStyles(3);
          break;
        case "KeyS":
          returnStyles(4);
          break;
        case "KeyD":
          returnStyles(5);
          break;
        case "KeyZ":
          returnStyles(6);
          break;
        case "KeyX":
          returnStyles(7);
          break;
        case "KeyC":
          returnStyles(8);
          break;
        default:
          return null;
      }
    } else {
      return null;
    }
  }

  useEffect(() => {
    window.addEventListener("keyup", makeButtonGray);

    return () => {
      window.removeEventListener("keyup", makeButtonGray);
    };
  });

  return (
    <div
      id="button-container"
      aria-label="Nine drum pad buttons. Press Q, W, E, A, S, D, Z, X, or C."
    >
      {state.drumKitData.buttonList.map((btn, index) => (
        <button
          key={btn.letter}
          ref={(dpad) => (buttonRef.current[index] = dpad)}
          aria-label={
            state.isPowerOn
              ? state.drumKitData.buttonList[index].displayText +
                ", or press '" +
                btn.letter +
                ".'"
              : state.drumKitData.buttonList[index].displayText +
                ". Power is off"
          }
         
          onMouseDown={handleAudioClick}
          onMouseOver={state.isPowerOn ? buttonHover : null}
          onMouseUp={() => mouseUpReturnStyles(index)}
          onMouseOut={buttonExit}
          onFocus={buttonHover}
          onBlur={buttonExit}
          className="drum-pad"
          tabIndex={0}
          id={btn.letter}
        >
          {btn.letter}
          <audio
            className="clip"
            id={btn.letter}
            ref={(ele) => (audioRef.current[index] = ele)}
            src={btn.url}
            preload="true"
          />
        </button>
      ))}
    </div>
  );
}

function Controls() {
  return (
    <div id="controls">
      <Power />
      <Volume />
      <Display />
      <Bank />
    </div>
  );
}

function Power() {
  const state = useContext(GlobalStateContext);
  const dispatch = useContext(DispatchContext);

  var powerButtonLabel = state.isPowerOn
    ? "Power button. Power is switched on."
    : "Power button. Power is switched off.";

  function switchPower() {
    dispatch({ type: ACTIONS.TOGGLE_POWER });
  }

  return (
    <div id="power">
      <button
        aria-label={powerButtonLabel}
        aria-live="polite"
        className={state.isPowerOn ? "power-on" : "power-off"}
        id="power-button"
        onClick={switchPower}
      >
        <FontAwesomeIcon icon={faPowerOff} aria-hidden="true" />
      </button>
    </div>
  );
}

function Volume() {
  const dispatch = useContext(DispatchContext);

  function changeVolume(e) {
    let currentVolume = (e.target.value / 100).toFixed(2);
    dispatch({ type: ACTIONS.CHANGE_VOLUME, payload: currentVolume });
  }

  return (
    <div id="volume">
      <label htmlFor="volume-switch" id="volume-switch-label">
        Volume
      </label>
      <input
        aria-labelledby="volume-switch-label"
        id="volume-switch"
        name="volume-switch"
        type="range"
        min="0"
        max="100"
        onInput={changeVolume}
      ></input>
    </div>
  );
}

function Display() {
  const state = useContext(GlobalStateContext);

  return (
    <div
      id="display"
      tabIndex={0}
      aria-label={
        state.isPowerOn
          ? "Display screen says: " + state.displayText + "."
          : "Empty display screen."
      }
    >
      <p>{state.isPowerOn ? state.displayText : " "}</p>
    </div>
  );
}

function Bank() {
  const state = useContext(GlobalStateContext);
  const dispatch = useContext(DispatchContext);

  return (
    <div id="bank">
      <div
        title="switch sound bank"
        id="bank-switch-holder"
        onClick={() => dispatch({ type: ACTIONS.TOGGLE_BANK })}
      >
        <input
          type="button"
          aria-label={
            state.isPowerOn
              ? state.drumKitData.displayText + " is active. Switch sound bank."
              : "Switch sound bank. Power is off."
          }
          className={state.kitOneIsActive ? "switched" : null}
          id="bank-switch"
        ></input>
      </div>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

              
            
!
999px

Console