lehermj
lehermj

Reputation: 936

How do I play a random sound on button click? JavaScript

When I press a button I want to play a random sound. but when I click it throws the error: "Cannot read property 'play' of null". Do I have to declare the audio variable somewhere else? or did I just misspell something? Anyways, here's my code so far:

var audio1 = document.getElementById("potato");


function burn1() {
    audio1.play();
}

function burn2() {
    audio1.play();
}

function burn3() {
    audio1.play();
}

function burn4() {
    audio1.play();
}

function burn5() {
    audio1.play();
}

function random() {
    var rand = Math.floor(Math.random() * (5 - 1)) + 1;
    switch(rand) {

        case 1:
            burn1();
            break;
        case 2:
            burn2();
            break;
        case 3:
            burn3();
            break;
        case 4:
            burn4();
            break;
        case 5:
            burn5();
            break;

    }
}

also, here's my HTML:

<!doctype HTML>
<html> 

    <head>
        <title>Burn Generator!</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>

    <body>
        <script type="text/javascript" src="main.js"></script>
        <span id="dummy"></span>
        <button id="burn" onClick="random()">OOOHH BURN!</button>
        <audio id="potato" src="Kalimba.mp3" ></audio>

    </body>

</html>

Upvotes: 0

Views: 2161

Answers (1)

sabithpocker
sabithpocker

Reputation: 15566

Put your script at the end of HTML, or use a ready callback. It makes sure that audio#potato is loaded when you are trying to access it. Right now audio1 will probably be undefined as the element is not existing at the time the code is run

<head>
    <title>Burn Generator!</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <span id="dummy"></span>
    <button id="burn" onClick="random()">OOOHH BURN!</button>
    <audio id="potato" src="Kalimba.mp3" ></audio>
    <script type="text/javascript" src="main.js"></script>
</body>

or use

document.addEventListener('DOMContentLoaded', function () {

});

in your code

Upvotes: 1

Related Questions