How to fix double click in this neoscript?

Wrote this thing himself, greasers, not cut, for all that had the mind that wrote.
The essence of the thing: clicking on the button should play a music, a kind of Neoplan
<div id="toggle_music" style="border-radius: 50px;background: #000; padding:10px;text-align: center; color:#fff; width:5%;cursor: pointer;">Knopochka</div>

<audio id="music" class>
<source src="assets/music_array/xxx.mp3" type="audio/mp3">
</audio>


actually it is prescribed, voproizvodit music, pressing the music turned off, but to re-play the music you need to click the button 2 times, 2 times write the class off in the audio tag, and then class on

var music = document.getElementById('music'); 
 music.volume = 0.1;
 $('#toggle_music').click(function(event){ //while there is no class in the audio tag, when you click the button you add the class on in the audio tag, music included
$('#music').addClass('on');
music.play();

 if ($('#music').hasClass('on')) { //if the found class is on, remove it and add the class off, the music Gasim
$('#toggle_music').click(function(event){
$('#music').removeClass('on');
$('#music').addClass('off');
music.pause();
});
}
 if ($('#music').hasClass('off')){
 $('#toggle_music').click(function(event) {//if found the class off, delete it and add a class on the music included
$('#music').removeClass('off');
$('#music').addClass('on');
music.play();
});
}
 });
June 3rd 19 at 21:01
1 answer
June 3rd 19 at 21:03
Solution
Code is not tested.
const music = document.getElementById('music');
music.volume = 0.1

music.addEventListener('click', () => {
music.classList.toggle('active')

 if (music.className.indexOf('active') === -1)
music.pause()
else
music.play()
})


The error you have is that when you click you don't check the class. Check out the class event handler. You first check, then initialize the handler.
At the expense of knowledge of JQuery, I do not know really!)
Thanks for the reply, will check it out. - orlando.Bode8 commented on June 3rd 19 at 21:06
Yes, indeed, it worked!

Just had to add another variable, the variable button.
const music = document.getElementById('music'); 
 music.volume = 0.1;
 const toggle_btn = document.getElementById('toggle_music')



 toggle_btn.addEventListener('click', () => {
music.classList.toggle('active')

 if (music.className.indexOf('active') === -1)
music.pause()
else
music.play()
 })


Thank you very much! - orlando.Bode8 commented on June 3rd 19 at 21:09
, :) Mark ? - Myrtis commented on June 3rd 19 at 21:12
noted ;) - orlando.Bode8 commented on June 3rd 19 at 21:15

Find more questions by tags JavaScriptjQuery