Обработчик на динамический audio
Допустим я создаю динамически audio элемент на странице. Для всех audio, которые были на страницы событие play работает, но для вновь созданного - нет. Понятно почему, но как это исправить ? (Если можно, конечно)
Пытаюсь что-то подобное, но не работает.
$(document).on('play','audio',function(){ .. })
$('button.add').click(function(){
$('div.append').append('<audio controls><source src="https://cdn.drivemusic.me/dl/online/pG3iszQQHYzthoyGyirc7Q/1637257810/download_music/2013/08/alex-hepburn-under-radio-version.mp3" type="audio/mp3"></audio>')
})
$(function(){
$('audio').on('play',function(){
$('audio').addClass('stoped');
$(this).removeClass('stoped').addClass('playing');
$('.stoped').each(function() {
$(this)[0].pause();
$(this)[0].currentTime = 0;
})
})
})
// Такая конструкция, которая могла бы помочь с динамическими элементами - не работает.
$(document).on('load','audio',function(){
console.log('da');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Заранее добавленные audio. Выключаются, если "один из" играет.</p>
<audio controls>
<source src="https://cdn.drivemusic.me/dl/online/pG3iszQQHYzthoyGyirc7Q/1637257810/download_music/2013/08/alex-hepburn-under-radio-version.mp3" type="audio/mp3">
</audio>
<audio controls>
<source src="https://cdn.drivemusic.me/dl/online/pG3iszQQHYzthoyGyirc7Q/1637257810/download_music/2013/08/alex-hepburn-under-radio-version.mp3" type="audio/mp3">
</audio>
<p>Динамически созданные audio не будут выключать остальные, если начать их проигрывать, но заранее добавленные спокойно выключают новые</p>
<div class="append"></div>
<button class="add">Add</button>
Ответы (1 шт):
Автор решения: sousage1212
→ Ссылка
Спасибо Алексей Шиманский и phpBear.
Наговнокодил такой смешанный вариант
document.addEventListener('play', function(e){
if(e.target.nodeName == 'AUDIO'){
$('audio').addClass('stoped');
$(e.target).removeClass('stoped').addClass('playing');
$('.stoped').each(function() {
$(this)[0].pause();
$(this)[0].currentTime = 0;
})
}
}, true);
Также нашел инфу на eng версии, как можно использовать $(document).on('play'..
Шаг 1
$.createEventCapturing = (function () {
var special = $.event.special;
return function (names) {
if (!document.addEventListener) {
return;
}
if (typeof names == 'string') {
names = [names];
}
$.each(names, function (i, name) {
var handler = function (e) {
e = $.event.fix(e);
return $.event.dispatch.call(this, e);
};
special[name] = special[name] || {};
if (special[name].setup || special[name].teardown) {
return;
}
$.extend(special[name], {
setup: function () {
this.addEventListener(name, handler, true);
},
teardown: function () {
this.removeEventListener(name, handler, true);
}
});
});
};
})();
Шаг 2
$.createEventCapturing(['play', 'pause']);
$(document).on('play', function(e){
});
Источник - https://stackoverflow.com/questions/11291651/why-dont-audio-and-video-events-bubble
И то и то работает как надо