JQuery toggle class

I'm having trouble adding the jQuery toggleClass function to the rest of my code. There are several HTML5 tags on this page that are managed through jQuery. I tried to add a switch function to the jQuery audio control function, but this is not adding a class, and then the audio control does not work .. so I assume this is some kind of strange syntax error.

What do you guys recommend? Below is jsFiddle and my (unfortunately) weak attempt :)

http://jsfiddle.net/danielredwood/FTfSq/10/

HTML:

<div id="music_right"> <div class="thumbnail" id="paparazzi"> <a class="playback"> <img class="play" src="http://www.lucisz.com/imgs/play.png" /> </a> <audio> <source src="../audio/fernando_garibay_paparazzisnlmix.ogg" type="audio/ogg" /> <source src="../audio/fernando_garibay_paparazzisnlmix.mp3" type="audio/mpeg" /> Your browser does not support HTML5 audio. </audio> </div> <div class="thumbnail" id="danceinthedark"> <a class="playback"> <img class="play" src="http://www.lucisz.com/imgs/play.png" /> </a> <audio> <source src="../audio/fernando_garibay_danceinthedark.ogg" type="audio/ogg" /> <source src="../audio/fernando_garibay_danceinthedark.mp3" type="audio/mpeg" /> Your browser does not support HTML5 audio. </audio> </div> <div class="thumbnail" id="bornthisway"> <a class="playback"> <img class="play" src="http://www.lucisz.com/imgs/play.png" /> </a> <audio> <source src="../audio/fernando_garibay_bornthisway.ogg" type="audio/ogg" /> <source src="../audio/fernando_garibay_bornthisway.mp3" type="audio/mpeg" /> Your browser does not support HTML5 audio. </audio> </div> </div> 

JavaScript:

 var curPlaying; $(function() { $(".playback").click(function(e){ e.preventDefault(); var song = $(this).next('audio')[0]; song.toggleClass("playing"); if(song.paused){ song.play(); if(curPlaying) $("audio", "#"+curPlaying)[0].pause(); } else { song.pause(); } curPlaying = $(this).parent()[0].id; }); }); //the function below works, but doesn't have the add/remove class functions 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; }); }); 
+6
source share
2 answers

I would use .addClass() and .removeClass() , as it will clear your code a bit and allow you to use CSS to execute all this layout:

 $('thumbnail').toggle(function(){ $('.play', this).removeClass('pausing'); $('.play', this).addClass('playing'); }, function(){ $('.play', this).addClass('pausing'); $('.play', this).removeClass('playing'); }); 
+5
source
 $('thumbnail').toggleClass('pausing playing'); 

ToggleClass . Add or remove one or more classes from each element in the set of matched elements, depending on the presence of the class or the value of the switch argument.

+15
source

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


All Articles