Week 13:

Scripting Media



We have already explored how to incorporate audio and video files into our HTML, but we can also control the playback and various properties of these media assets using JavaScript.

play

pause

document.querySelector("#box1").addEventListener("click", function(){
    document.querySelector("#nwa").play();
});

document.querySelector("#box2").addEventListener("click", function(){
    document.querySelector("#nwa").pause();
});

jQuery is slightly different in its approach to controlling media elements.

play

pause

$(document).ready(function(){
    $("#box3").click(function(){
        $("#nwa").trigger("play");
    });
    $("#box4").click(function(){
        $("#nwa").trigger("pause");
    });
});

A little additional logic and reading the paused property from the audio HTML element allows us to toggle playing and pausing the audio with a single button. Note that we need to use the vanilla JavaScript document.querySelector() method to access the HTML media element in order to have access to the paused property.

play/pause

$(document).ready(function(){
    $("#box5").click(function(){
        var obj = document.querySelector("#nwa");
        if(obj.paused){
            obj.play();
        } else {
            obj.pause();
        }
    });
});

We can control the volume of audio elements. Use one of the buttons above to play the song and adjust the volume using the slider below.


$(document).ready(function(){
    $("#volumeslider").on("input change", function(){
        var vol = $(this).val() * 0.01;
        $("#nwa").prop("volume", vol);
    });
});

Resources