I have the following JS:
var links = document.getElementsByClassName('swoosh'),
audio = document.getElementById('a-on-click'),
clickHandler = function () {
audio.play();
}
;
for (var i in links) {
links[i].addEventListener('click', clickHandler);
}
For the following HTML:
Link 1
Link 2
Link 3
<audio id="a-on-click">
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
The script works like a charm, only activating the sound if the a has class="swoosh". However, the problem appears when the link in the href is an actual link and not a #.
I did some research on SO and Google. I thought that preventDefault() would be the solution here, however I'm starting to doubt that because what I want is for the sound file to play and then redirect to the location specified in the href, not to stop the link functionality entirely. The solution should also only apply to links that have the "swoosh" class.
How is this achievable?
You can find a JSFiddle to play with here.
Rahul's got it; then, wait til the audio finishes and then navigate.
var links = document.getElementsByClassName('swoosh'),
audio = document.getElementById('a-on-click'),
clickHandler = function(event) {
event.preventDefault();
audio.addEventListener('ended', function(){
window.location.href = event.target.href;
})
audio.play();
};
for (var i in links) {
links[i].addEventListener('click', clickHandler);
}
Link 1
Link 2
Link 3
<audio id="a-on-click">
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
To prevent immediate click effect use one of these inside your listener.
event.preventDefault() || event.stopPropagation();
When you are done playing sound add an event listener for when the sound ends to change the location of the current window.
window.location = event.target.href;
var links = document.getElementsByClassName('swoosh'),
audio = document.getElementById('a-on-click'),
clickHandler = function(event) {
event.preventDefault();
event.stopPropagation();
audio.play();
audio.addEventListener('ended', function(){
window.location = event.target.href;
})
};
for (var i=0; i < links.length; i++) {
links[i].addEventListener('click', clickHandler, true, true);
}
Link 1
Link 2
Link 3
<audio id="a-on-click">
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
Use event.preventDefault() in the clickHandler, it will block the default behavior of the links with that particular class:
var links = document.getElementsByClassName('swoosh'),
audio = document.getElementById('a-on-click'),
clickHandler = function(event) {
event.preventDefault();
audio.addEventListener('ended', function() {
window.location = event.target.href;
});
audio.play();
};
for (var i in links) {
typeof i === 'Number' && links[i].addEventListener('click', clickHandler);
}
Link 1
Link 2
Link 3
<audio id="a-on-click">
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
Docs: Event.preventDefault() - Web APIs | MDN
EDIT 1: Please use the audio.addEventListener from Ben's answer. He's got it.
EDIT 2: Changed code in for to check if i is Number type
EDIT 3: Your href is incorrect. Use the one below:
clickHandler = function(event) {
var href = this.href; // cache href here
event.preventDefault();
event.stopPropagation();
audio.play();
audio.addEventListener('ended', function(){
window.location = href; // use cached href here
})
};
Related
I would like to implement an audio player on all of my WordPress pages and therefore I need to create the HTML element with JS and manipulate it from there. Everything is working, except for when I press the play button, it redirects me to a new page with the audio link and plays it there. I would like to prevent that, so that I can play and stop it on the WP pages themselves and have the audio play in the background.
Any tips are greatly appreciated!
function addAudioPlayer() {
const audioPlayer = document.createElement("a");
audioPlayer.setAttribute("id", "audioPlayer");
audioPlayer.href =
"https://www.hostname.com/wp-content/uploads/2020/09/bird_sound.wav";
audioPlayer.setAttribute("data-id", "[data-song]");
audioPlayer.innerHTML = "▶";
Array.prototype.forEach.call(
document.querySelectorAll("[data-song]"),
function (song) {
song.audio = new Audio(song.href);
song.setAttribute("role", "button");
song.setAttribute("aria-pressed", "false");
}
);
document.addEventListener("click", function (event) {
if (!event.target.hasAttribute("data-song")) return;
event.preventDefault();
if (event.target.getAttribute("aria-pressed") == "true") {
event.target.audio.pause();
event.target.setAttribute("aria-pressed", "false");
return;
}
event.target.audio.play();
event.target.setAttribute("aria-pressed", "true");
},
false
);
document.body.appendChild(audioPlayer);
}
<div>
<audio id="myaudio" src="https://www.hostname.com/wp-content/uploads/2020/09/bird_sound.wav" controls="controls" preload="auto" hidden="true"></audio>
<input type="button" onclick="autoPlay()" value="Play"/>
</div>
<script language="javascript" type="text/javascript">
var myAuto = document.getElementById('myaudio');
function autoPlay(){
myAuto.play();
}
</script>
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);
}
}
How can I change a property of a source element / video object.
In my case I want to change the property autostart from false to true;
html:
<video id="modul_1_video" controls preload="none">
<source id="modul_1_source" src="../video.mp4" type="video/mp4" autostart="false">
</video>
js: (I do not want to use jquery)
modul_1.onclick = function() {
console.log("click works");
document.querySelector("#modul_1_video > source").autostart = true;
}
but it does not seem to work.
why don't you just use the play function?
modul_1.onclick = function() {
console.log("click works");
var video = document.getElementById("#modul_1_video");
video.play();
}
set "autostart" attribute to true on click
document.getElementById('modul_1_source').setAttribute('autostart','true');
modul_1.onclick = function() {
console.log("click works");
document.getElementById("#modul_1_video").setAttribute("autostart","true");
}
I have many audio elements on a single page and I want to play just one element at a time. That is if one audio element is playing and I click on play on another element, the previous audio element should pause.
I found a jQuery code from another question to do this but that uses an image as play/pause controls. I'm using the inbuilt controls='controls' attribute for the audio element instead. Is it possible to use jQuery to control the play/pause feature for the audio element in my case?
Here is my HTML code
<div>
<p class="song"><h3><strong>#1 Intro - The Oath</strong></h3><p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
<div>
<p class="song"><h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3></p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
Here is the jQuery code
$(document).ready(function() {
var curPlaying;
$(function() {
$(".playback").click(function(e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if(song.paused){
song.play();
if(curPlaying) $("audio", "#"+curPlaying)[0].pause();
} else { song.pause(); }
curPlaying = $(this).parent()[0].id;
});
});
});
The jQuery code doesn't seem to be working for me.
$(function(){
$("audio").on("play", function() {
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
});
See sample at JSFiddle
Vanilla JS solution
Here's a solution that doesn't require jQuery.
function onlyPlayOneIn(container) {
container.addEventListener("play", function(event) {
audio_elements = container.getElementsByTagName("audio")
for(i=0; i < audio_elements.length; i++) {
audio_element = audio_elements[i];
if (audio_element !== event.target) {
audio_element.pause();
}
}
}, true);
}
document.addEventListener("DOMContentLoaded", function() {
onlyPlayOneIn(document.body);
});
Some things to note:
Because this listens for events on a parent element, not on the audio elements themselves, they can be added or removed after the page is loaded and it will still work.
It watches for the play event in the capture phase because play events don't bubble.
More media events are described here on MDN.
Listening for "DOMContentLoaded" should work for most browers.
Little Modification to LostInComputer's Answer
In Your HTML Write:
<audio controls onplay="pauseOthers(this);" >
<source src="SourcePath">
</audio>
In Js Write:
function pauseOthers(ele) {
$("audio").not(ele).each(function (index, audio) {
audio.pause();
});
}
Assuming that your syntax for stopping and pausing tracks is correct (I don't know anything about the audio element), you should be able to do something like this:
$(".playback").click(function(e) {
// pause all other tracks
$('.audio').each(function () {
var song = this;
if (!song.paused) { song.pause(); }
});
// play the audio associated with this element
this.play();
});
<script>
function controlplay(e) {
document.querySelectorAll('.playback').forEach(item => { if(item.id != e.target.id) item.pause(); });
}
</script>
<script>
document.querySelectorAll('.').forEach(item => { item.addEventListener("play", event => { controlplay(event) })});
</script>
Angular:
<audio (play)="audioPlay($event)" controls preload="none">
<source [src]="url" type="audio/mpeg">
</audio>
audioPlay(e) {
let eAudio = this.domService.getDocument.getElementsByTagName('audio')
if (eAudio && eAudio.length > 0) {
for (var i = 0; i < eAudio.length; i++) {
if(e.target !== eAudio[i]){
eAudio[i].pause();
}
}
}
}
<script>
var nowplaying = null;
// Pause and reset playing audio before starting new selection
function pauseRunningAudio(id) {
if ( nowplaying != null && nowplaying != id) {
var x = document.getElementById(nowplaying);
x.pause();
x.load();
}
nowplaying = id;
}
</script>
<!-- id and function value must be the same -->
<audio controls onplay="pauseRunningAudio('song1')" id="song1">
<source src="Bohemian Rhapsody.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song2')" id="song2">
<source src="November Rain.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song3')" id="song3">
<source src="Smoke on the Water.mp3" type="audio/mpeg">
</audio>
I have a content slider, set to play / stop on each click.
The problem: I want it to pause on second click. Right now it won't pause. Any ideas?
See site here: http://dev.alsoknownas.ca/music/ (audio branding section on homepage).
Here's the code:
**Edited to reflect the code suggested by Lloyd below:
<audio id="player"></audio>
Here's the script:
$(document).ready(function(){
$("span.1").attr("data-src","song.mp3");
$("span.2").attr("data-src","song2.mp3");
$("span.3").attr("data-src","song3.mp3");
$("span.4").attr("data-src","song4.mp3");
$("span.5").attr("data-src","song5.mp3");
});
$("span.1,span.2,span.3,span.4,span.5").click(function () {
var player = document.getElementById("player");
player.src = this.getAttribute("data-src");
player.play();
});
for this markup:
<audio id="player"></audio>
<span class="1">one</span>
<span class="2">two</span>
use this script:
$("span.1")
.attr("data-src-mp3","song1.mp3")
.attr("data-src-ogg","song1.ogg");
$("span.2")
.attr("data-src-mp3","song2.mp3")
.attr("data-src-ogg","song2.ogg");
$("span[data-src-mp3]").click(function () {
var player = document.getElementById("player"),
$this = $(this);
if ($this.hasClass("selected")) {
if (player.paused) {
player.play();
} else {
player.pause();
}
}
else {
$("span[data-src-mp3].selected").removeClass("selected");
$this.addClass("selected");
$(player)
.empty()
.append($("<source>").attr("src", $this.attr("data-src-mp3")))
.append($("<source>").attr("src", $this.attr("data-src-ogg")))
player.play();
}
});
Live Demo: http://jsfiddle.net/75lb/8cGBx/
Try this,
Instead of doing
$('audio').bind('play','pause', function() {
Do
$('audio').bind('play pause', function(event) {
According to your code, by default audio is paused, when user clicks, it starts playing, and on next click it pauses.
Hope this works for you.