I am trying to figure out how to trigger an audio file when a button is hovered and has a specific number displayed it will play a specific audio file.
The first code does not work for me.
The second code works but not correctly and some how doesnt take into consideration what is being displayed on the button.
//First-Code - Assigns answer-buttons with an event listener
document.getElementById('answer-buttons').addEventListener("mouseover", answerHoverButtonAudio);
//Button Function to call answerHoverButtonAudio
function answerHoverButtonAudio() {
if (document.getElementById('answer-buttons').innerText == ('1')) {
var audio = document.getElementById('Number-1')
audio.play();
}
}
//Second-Code - This code below triggers the audio but does it no matter what text is showing on the button somehow.
//Assigns answer-buttons with an event listener
document.getElementById('answer-buttons').addEventListener("mouseover", answerHoverButtonAudio);
//Button Function to call answerHoverButtonAudio
function answerHoverButtonAudio() {
if (answerButtonsElement.innerText.includes('1')) {
var audio = document.getElementById('Number-1')
audio.play();
}
}
You can use event passed via mouseevent listener which can check innerText to play particular audio.
code sandbox - https://codesandbox.io/s/amazing-hypatia-j76ggx?file=/src/index.js
const answerHoverButtonAudio = (event) => {
if (event.currentTarget.innerText.includes("1")) {
debugger;
var audio = document.getElementById("Number-1");
audio.play();
}
};
document
.getElementById("answer-buttons")
.addEventListener("mouseover", answerHoverButtonAudio);
<div id="answer-buttons">1</div>
<audio controls id="Number-1">
<source src="https://www.w3schools.com/tags/horse.ogg" type="audio/ogg" />
Your browser does not support the audio element.
</audio>
Related
I have a page with some videos. I want to implement the ability to click on a button to make a video play and if I click another button the current video will stop and the next video will start playing.
How can something like this be achieved?
My project is similar to Netflix's main page.
My Website:
https://capcom2store.com/mov4k.php
This is my JS:
<script>
var videoElement = document.getElementById("myVideo");
function playPause() {
if (videoElement.paused) {
videoElement.play();
} else {
videoElement.pause();
}
};
</script>
One of the things you can do is to do something similar to the following:
// Get all video elements on the current page
const videoElements = document.querySelectorAll("video");
for (const videoEl of videoElements) {
// Listen to clicks on every one of the videos
videoEl.onclick = () => {
if (videoEl.paused) {
for (const video of videoElements) {
// When starting to play one video, pause all others
video.pause();
}
videoEl.play();
} else {
videoEl.pause()
}
}
}
<video src="https://www.w3schools.com/html/mov_bbb.mp4"></video>
<video src="https://www.w3schools.com/html/mov_bbb.mp4"></video>
Although this is a very simple example, because it takes over all of the click events of the video elements. It would be better to detect clicks another way (like having an overlay element or a button)
I tried to make a metronome using HTML and JS. I know the audio can't autoplay due to restrictions (I don't want it to anyway), so I placed an <audio ...> element with a <source ...> inside, with all (I thought?) appropriate attributes; I controlled playback using JS triggered by a button click. This works on my laptop and even in the XBox Edge browser, but on iOS browsers (both Safari and Firefox) the sound does not play. The HTML looks like this:
<button id="metronome-button">Start</button>
<audio id="metronome-audio" autoplay="0" autostart="0" loop="0">
<source src="tick.mp3" type="audio/mpeg">
</audio>
And the JS looks like this:
const metronomeAudio = document.getElementById('metronome-audio');
const metronomeButton = document.getElementById('metronome-button');
let metronomeInterval = null;
metronomeButton.addEventListener('click', () => {
metronomeInterval = setInterval(() => {
metronomeAudio.loop = false;
metronomeAudio.pause();
metronomeAudio.play();
}, 500);
});
Since this didn't work, I did more looking and found this solution in another StackOverflow thread, which uses JS and no HTML at all (other than being triggered by a button's click event):
function startMetronome () {
setInterval(() => {
let audio = new Audio('tick.mp3');
audio.loop = false;
audio.play();
audio.onended = () => {
audio.remove();
}
}, 500);
}
Again, this works on PC in various browsers, why does this fail specifically on iOS? (Have not tested on Android, don't have device.)
I am not sure if this is documented anywhere (I didn't stumble across it), but after some additional testing I discovered that iOS prohibits use of the .play() function on an existing HTML <audio> element or JS Audio() element, unless called directly and synchronously as the result of a user UI event. In other words, this will work:
const button = document.getElementById('my-button')
const audio = document.getElementById('my-audio')
button.addEventListener('click', () => {
audio.play()
})
But this will not work:
const button = document.getElementById('my-button')
const audio = document.getElementById('my-audio')
button.addEventListener('click', () => {
setTimeout(() => { audio.play() }, 1000)
})
Thus, having the .play() call in an async callback breaks playback on iOS.
However, as mentioned in a comment on this answer here: https://stackoverflow.com/a/54432573/983173, if you instantiate your audio element within a synchronous user interaction event handler, you can re-use and re-play (e.g. .play()) an Audio() element as much as you like. For example:
const button = document.getElementById('my-button')
let audio = null
button.addEventListener('click', () => {
audio = new Audio('myAudio.mp3')
// Works because `audio` itself was created synchronously during user event handler
setTimeout(() => { audio.play() }, 1000)
})
What exactly is wrong with my selection?
<audio id="cart_add_sound" controls="" preload="auto" hidden="hidden"> <source src="img/cart_add.wav"
type="audio/wav"> </audio>
creating a function
targeting class button-4
attaching an even listener to mouse click
and play the audio with an id of cart_add_sound
// Play Audio on Add to Cart
function playAudio() {
var play = document.querySelector('.button-4')
play.addEventListener('click', function() {
document.getElementById('cart_add_sound').play();
}, true);
}
i know i could use inside html5 onclick="audio.play()" but i want to approach it this way for learning purpose.
You should initialize / execute this function, for example, after the DOM is ready:
// Play Audio on Add to Cart
function playAudio() {
var play = document.querySelector('.button-4')
play.addEventListener('click', function() {
document.getElementById('cart_add_sound').play();
}, true);
}
// DOM ready event
document.addEventListener('DOMContentLoaded', (event) => {
playAudio();
});
Have you run it somewhere?
Demo - https://codepen.io/vyspiansky/pen/BaKKdvW
i fixed it by using getElementsByClassName
and looping through all elements.
// Play Audio on Add to Cart
function playAudio() {
var plays = document.getElementsByClassName('button-4')
for (var i = 0; i < plays.length; i++) {
var play = plays[i]
play.addEventListener('click', function() {
document.getElementById('cart_add_sound').play();
}, true);
}
}
I am working on my portfolio site to make it more ADA compliant when I noticed a lot of redundant code that I want to optimize. I have seven videos on the screen and each have a onmouseover and onmouseout event attributes. I wanted to create a JavaScript that just assigned these event handlers to all video tags on the screen in one function run on startup.
This worked using html code
<video class="nlm-marque-video" id="aerialVideo">
<source src="videos/aerial-view-of-san-diego.mp4"
onmouseover = "playVid(this);"
onmouseout ="pauseVid(this);"
type="video/mp4">
</video>
<script>
/*
* get reference of all video tags on page
* set the video attributes to same defaults
* start videos automatically the first time with muted
*/
function videoEnhance(){
let vid = document.getElementsByTagName("video");
for (i=0;i<vid.length; i++) {
vid[i].autoplay = true;
vid[i].muted = true;
vid[i].controls = true;
vid[i].addEventListener("onmouseover", playVid(this));
vid[i].addEventListener("onmouseout", pauseVid(this));
}
}
/*
* function to play video event
*/
function playVid(vidObj) {
vidObj.play();
console.log("video is playing");
}
/*
* function to pause video on event
*/
function pauseVid(vidObj) {
vidObj.pause();
console.log("video is paused");
}
</script>
index.php:346 Uncaught TypeError: vidObj.play is not a function
at playVid (index.php:346)
at videoEnhance (index.php:338)
at onload (index.php:24)
playVid # index.php:346
videoEnhance # index.php:338
onload # index.php:24
The videos runs, but do not respond to the mouseover and mouseout events.
I think that your simplest solution would probably be to just use the event to play and pause things.
function videoEnhance(){
let vid = document.getElementsByTagName("video");
for (i=0;i<vid.length; i++) {
vid[i].autoplay = true;
vid[i].muted = true;
vid[i].controls = true;
vid[i].addEventListener("mouseover", playVid); //Don't pass in param here.
vid[i].addEventListener("mouseout", pauseVid); //Or here
}
function playVid(e) {
e.target.play(); //use the event
console.log("video is playing");
}
function pauseVid(e) {
e.target.pause(); //use the event
console.log("video is paused");
}
}
I have an <audio> object that might need to load before it can play, is there a way to trigger a function when either the sound begins after downloading, or when the user clicks the play button?
There is a playing event you can listen to like so.
audio.addEventListener("playing", function() {
console.log("playing");
});
http://w3c.github.io/html/semantics-embedded-content.html#eventdef-media-playing
Yes, there is onplay event for audio and video, you should use <audio> tag to do it
var audio = document.getElementById("Your_audio");
audio.onplay = function() {
//your code
};
with the javascript audio object you can add some event listener, like :
var horn = new Audio('car_horn.wav');
horn.addEventListener('loadeddata', () => {
let duration = horn.duration;
// The duration variable now holds the duration (in seconds) of the audio clip
})
as you can see here : https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement
you can simply add an evenListner like this:
<audio|video onplay="myScript">
e.g. you can do like this:
var aud = document.getElementById("myAudio");
aud.onplay = function() {
alert("The audio has started to play");
};