5
[Vue.js] Play Audio Sound on Click Event of DOM Element
source link: http://siongui.github.io/2017/02/23/vuejs-play-audio-sound-onclick-event/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[Vue.js] Play Audio Sound on Click Event of DOM Element
February 23, 2017
Play audio sound if uers click on DOM Element in Vue.js/JavaScript.
The key points of the following source code:
- Use v-on directive to attach event listener of button onClick event.
- Use ref attribute to register a reference to audio element. We will later access the audio element by the unique reference name audioElm in the event listener.
- If users click on the button, call play() method of the audio element to play the sound.
index.html | repository | view raw
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Vue.js Play Audio Sound Onclick Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id="app"> <button v-on:click="play" type="button">Click Me to Play Sound</button> <audio ref="audioElm" src="../../javascript/play-toggle-sound/Wat_Metta_Buddha_Qualities.mp3"></audio> </div> <script src="https://unpkg.com/[email protected]/dist/vue.js"></script> <script src="app.js"></script> </body> </html>
app.js | repository | view raw
'use strict'; var app = new Vue({ el: '#app', methods: { play: function(event) { this.$refs.audioElm.play(); } } })
Tested on:
- Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
- Vue.js 2.1.10.
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK