'Play audio once when div is visible
using jQuery 3.4.1 - I have set up a system where an administrator when logged in will have a script running every 5 seconds to check if any users have initiated a chat request. If so a window will appear with the users name and their initial question/message.
As well as the window I want to play an alert sound to let the admin know when a chat request is made but the issue is if I put the audio inside the script which checks for chat requests it will play immediately (if they log in and there's already a chat request) and then every 5 seconds which is very irritating.
To remedy I tried checking if the chat request div is visible then play the sound but it won't play at all this way and I'm not getting any console messages about it - I think this is happening because the sound requires user interaction in order to play.
Here's my current code.
// Chat Request Notification Sound (not working)
var chatstartsound = new Audio('../img/root/start.wav');
if ($('#chatrequest').is(":visible"))
{ chatstartsound.play(); }
// Chat Request
(function chatrequest() {
$.ajax({
url:"../inc/chat-request.php",
method:"POST",
context: document.body, // This is to stop the AJAX spinner appearing every 5 seconds.
global: false, // This is to stop the AJAX spinner appearing every 5 seconds.
success:function(data) {
$("#chatrequest").html(data);
$("#chatrequest").delay(5000).show(200);
}
}).then(function() {
setTimeout(chatrequest, 5000);
});
})();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
