adding class and removing class on click - javascript

I have audio player and i made on button click for music to stop and play again but i want to change icon on it aswell, but i dont know how to add i class and remove it on click, thanks. Here is my code, i want to remove fa-pause and add fa-play
var player = document.getElementById("player");
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
player.pause()
} else {
player.play();
}
};
player.onplaying = function() {
isPlaying = true;
};
player.onpause = function() {
isPlaying = false;
};
<button class="button" onclick="togglePlay()"><i class="fas fa-pause"></i></button>

First add an id for your play/pause button.
<button id="control-btn" class="button" onclick="togglePlay()"><i class="fas fa-pause"></i></button>
Then select the <i class="fas fa-pause"></i> item and remove/add the class
var player = document.getElementById("player");
var isPlaying = false;
function togglePlay() {
var item = document.querySelector("#control-btn i");
if(isPlaying) {
player.pause();
item.classList.remove("fa-pause");
item.classList.add("fa-play");
} else {
player.play();
item.classList.remove("fa-play");
item.classList.add("fa-pause");
}
};
player.onplaying = function(){
isPlaying = true;
};
player.onpause = function(){
isPlaying = false;
};

Here is a working example. Your code contains needed few refactoring since you are using html only. I would recommend you use jquery to simplify the code.
https://jsfiddle.net/c5ystb4t/16/
code below is your sample.
var player = document.getElementById("player");
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
player.pause()
} else {
player.play();
}
};
player.onplaying = function() {
isPlaying = true;
};
player.onpause = function() {
isPlaying = false;
};
<button class="button" onclick="togglePlay()"><i class="fas fa-pause"></i></button>

Just use the toggleClass method from classList:
document.getElementById( 'player' ).classList.toggleClass( 'fa-pause' )
document.getElementById( 'player' ).classList.toggleClass( 'fa-play' )
Make sure one of both classes is already active, otherwise both will activate or deactivate at once.
Edit I checked the docs on toggle and you can only do one class name per call.
document.getElementById( 'test' ).addEventListener('click', function( event ){
event.preventDefault();
event.target.classList.toggle( 'a' );
event.target.classList.toggle( 'b' );
})
.a { color: red !important; }
.b { color: yellow !important; }
Click me to toggle Classes
Docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
On a sidenote, you might want to get rid of your isPlaying variable and just use plater.paused, since it contains a boolean as well that you don't have to track, and therefor saves you a little bit of memory.

Related

Need simplified function for onclick button sounds

This is my first question here sorry if I make any mistake.
I want to know how to simplify an action (function), I have a drumkit with different buttons and sounds, I'm using this code: FIDDLE
JS
function play() {
var audio = document.getElementById('audio1');
if (audio.paused) {
audio.play();
} else {
audio.currentTime = 0
}
}
How can I write just one function and play different sounds for every button?
You could try firing multiple functions from one function. Something like:
<button onClick="play()">song1</button>
<button onClick="play()">song2</button>
<button onClick="play()">song3</button>
function someFunc() {
function audioOne() {
var audio = document.getElementById('audio1');
if (audio.paused) {
audio.play();
}
else{
audio.currentTime = 0
};
function audioTwo() {
var audio = document.getElementById('audio2');
if (audio.paused) {
audio.play();
}
else{
audio.currentTime = 0
};
function audioThree() {
var audio = document.getElementById('audio3');
if (audio.paused) {
audio.play();
}
else{
audio.currentTime = 0
};
}
Alternatively you could also try something like:
var audio = document.getElementById("id");
audio.addEventListener("click", function(){alert("audio1 triggered")}, false);
audio.addEventListener("click", function(){alert("audio2 triggered")}, false);
function play(id) {
var audio = document.getElementById(id);
if (audio.paused) {
audio.play();
}else{
audio.currentTime = 0
}
call it like this:
play('audio1');
play('audio2');
If i understand your question correctly this should work for your use-case. You basically just pass the elements id as parameter. Everytime you call the function the logic will apply to the element you specified as parameter in your function call.

Is there a way I could assign 2 separate functions on 2 onclick in a button?

I wanted to:
play the animation on my first click and
stop it on my second click of the same button.
Thanks.
Here is the simplest solution using closures, you should learn more on how closures work.
function generateMyStatefullFunction(){
var someState = false;
return function theActualFunctionThatDoesThings(){
if (someState){
console.log("State will be set to false, next click wont trigger this message");
}
someState = !someState;
}
}
var onClickHandler = generateMyStatefullFunction();
document.getElementById("button").addEventListener('click', onClickHandler);
<button id="button"> Fire every second click</button>
You can do like this
function performAction(event){
var button = event.currentTarget;
var action = button.innerHTML;
if(action == "Play"){
button.innerHTML = "Stop"
//play animation
} else {
button.innerHTML = "Play"
//stop animation
}
}
<div>
<button onclick="performAction(event)" >Play</button>
</div>

Preventing Jquery .click toggle function from running over and over with excess clicking

Im building a .clicktoggle function in jQuery and for the life of me i can't get a .stop like effect on it, basically i don't want it to play over and over if mash clicked.
I want it to be applied the the function so its self contained, that's where im stuck.
JS fiddle link
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
$('div').clickToggle(function() {
$('.testsubject').fadeOut(500);
}, function() {
$('.testsubject').fadeIn(500);
});
<div class="clickme">click me fast</div>
<div class="testsubject">how do i stop it playing over and over if you click alot</div>
Toggle .click seems like something alot of people would use so i thought it might be useful to ask it here
By adding a check to a boolean variable fadeInProgress, you can choose to only queue the animation if fadeInProgress is false. It then sets the value to true and executes the animation. When the animation is completed, set the value to false.
var fadeInProgress = false;
$('div').clickToggle(function() {
if (!fadeInProgress) {
fadeInProgress = true;
$('.testsubject').fadeOut(700, function(){fadeInProgress = false;});
}
}, function() {
if (!fadeInProgress) {
fadeInProgress = true;
$('.testsubject').fadeIn(700, function(){fadeInProgress = false;});
}
});
var clicked = false;
var doing = false;
$(".clickme").click(function(e) {
if (doing) {
return;
} else {
doing = true;
}
doing = true;
clicked = !clicked;
if (clicked) {
$('.testsubject').fadeOut(700, function() {
doing = false
});
} else {
$('.testsubject').fadeIn(700, function() {
doing = false;
});
}
});
This example is a simple toggle which only allows you to click when it is not doing anything. I explained on IRC, but as an example here, the function only runs when doing is set to false, which only happens when it's set after fadeIn() or fadeOut's callback function thingymajigger.

Soundcloud Javascript SDK sound not pausing

Using the Soundcloud JavaScript SDK I have successfully been able to grab my tracks and play them. My goal is to allow playing and pausing via clicking on one button (like a play/pause toggle). However, my issue is that when I click on the .SCbtn element, the song plays, and doesn't stop. My conditionals seem to be correct because I can see true and false making it into the console. Not quite sure why SC.sound.pause(); isn't working.
var is_playing = false;
var trackCont = function(trackNum){
SC.stream("/tracks/" + trackNum).then(function(sound){
SC.sound = sound;
if (is_playing === false){
SC.sound.play();
is_playing = true;
console.log(is_playing);
}else if(is_playing === true){
SC.sound.pause();
is_playing = false;
console.log(is_playing);
}
});
}
$('body').on("click", ".SCbtn", function(){
var theTrack = $(this).attr('id');
trackCont(theTrack);
});
Update
My Fiddle
I think you're overcomplicating things. Here's a simple example:
HTML:
<script src="https://connect.soundcloud.com/sdk/sdk-3.0.0.js"></script>
<button id="play">Play</button>
JavaScript:
SC.initialize({
client_id: 'XXXX'
});
var myPlayer;
var isPaused = false;
SC.stream('tracks/43377447').then(function(player){
player.play()
myPlayer = player;
});
document.querySelector('button').addEventListener('click', function() {
if (isPaused) {
myPlayer.play()
isPaused = false;
} else {
myPlayer.pause()
isPaused = true;
}
});
Working JSFiddle.
You should use the toggle() method provided by Soundcloud for easiest implementation. See here: https://developers.soundcloud.com/docs/api/html5-widget
Something like the below should do the trick:
var sc = SC.Widget(iframe);
$('body').on("click", ".SCbtn", function(){
sc.toggle();
});

how do i add two event listeners/actions to one button

i'm trying to make the pause and play on "button" but am not sure how to do it. im guessing it needs to know that one click is active to switch to the other, but im not sure how to do that.
// Initialize variables
var button = document.getElementById("button");
var button2 = document.getElementById("button2");
var rect = document.getElementById("rect");
var polygon = document.getElementById("polygon");
var circle = document.getElementById("circle");
// Define functions
function play() {
rect.setAttribute("class", "anim");
polygon.setAttribute("class", "anim");
circle.setAttribute("class", "anim");
}
function pause() {
rect.setAttribute("class", "pause");
polygon.setAttribute("class", "pause");
circle.setAttribute("class", "pause");
}
// Add event listeners
button.addEventListener("click", play, false);
button2.addEventListener("click", pause, false);
You can write a toggle handler instead:
function playPause()
{
if (this.playState) {
rect.className = polygon.className = circle.className = 'pause';
} else {
rect.className = polygon.className = circle.className = 'anim';
}
// update button text to indicate state?
this.playState = !this.playState;
}
It keeps a state on the DOM element itself and switches between paused and playing.
If you are using two different buttons then Try this,
var isplaying = false;
function play() {
isplaying = true;
rect.setAttribute("class", "anim");
polygon.setAttribute("class", "anim");
circle.setAttribute("class", "anim");
}
function pause() {
isplaying = false;
rect.setAttribute("class", "pause");
polygon.setAttribute("class", "pause");
circle.setAttribute("class", "pause");
}
// Add event listeners
button.addEventListener("click",function(){ if(!isplaying){
button.disable(); button2.enable(); play();}});
button2.addEventListener("click",function(){ if(isplaying){
button2.disable(); button.enable(); pause();}});

Categories

Resources