JQuery sound fades and pauses, onclick fades into audio and resumes

What is the problem? When I press the #background_audio div button, the sound disappears and then automatically fades out and continues to play without me, pressing the button again. How to fix it?

I try to make the sound disappear and pause when I click on the #background_audio button, and then when I press #background_audio sound disappears and resumes.

 <script type="text/javascript"> $(document).ready(function(){ $('#mute').click(function(){ $('#background_audio').animate({volume: 0}, 1000); setTimeout(function(){('#background_audio').pause()},1000); }); $('#mute').click(function(){ $('#background_audio').animate({volume: 1}, 1000); setTimeout(function(){('#background_audio').pause()},1000); }); }); </script> 
+4
source share
1 answer

You add two click handlers to one jQuery element, so two handlers are called with one click.

You need to add if to check if the sound is muted.

When you click on the button, the sound will be muted or muted using fadeIn.

HTML

 <div style="bottom:0; position:absolute; height:32px; width:100%;"> <button id="mute">Mute sound</button> <audio id="background_audio" src="http://www.noiseaddicts.com/samples/2541.mp3" autoplay="autoplay"></audio> </div> 

Javascript

 $(document).ready(function(){ var backAudio = $('#background_audio'); var muted = false; $('#mute').click(function(){ var button = $(this); if (!muted) { button.attr("disabled", ""); backAudio.animate({volume: 0}, 1000, function () { muted = true; button.removeAttr("disabled", ""); button.text("Unmute sound"); }); } else { button.attr("disabled", ""); backAudio.animate({volume: 1}, 1000, function () { muted = false; button.removeAttr("disabled", ""); button.text("Mute sound"); }); } }); }); 

JSFIDDLE

+4
source

Source: https://habr.com/ru/post/1486166/


All Articles