JS Button to toggle youtube embedded video - javascript

So I made a toggle button with JS functionality inside elementor plugin. When button clicked for the first time, the embedded video will play. When clicked after that, it'll pause. And when clicked again, it'll play again. And so on. Here's the code I've written:
const vid1 = document.getElementsByClassName("eicon-play")[0];
let santanVid = 'pausing';
document.getElementById("santan-thumb").onclick = () => {
if (santanVid = 'pausing') {
santanVid = 'playing'
} else if (santanVid = 'playing') {
santanVid = 'pausing'
}
if (santanVid = 'pausing') {
vid1.click();
$('.elementor-video')[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
} else if (santanVid = 'playing') {
vid1.click()
$('.elementor-video')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*')
}
};
The problem is, it only worked once. The first time I load the page, click the button and the video will play. Click the button the second time, and the video stop. But if I clicked again, the video won't play
I've tried using 2 button and the code is working, the problem occurs when I'm using 1 button as a toggle, and I'm curious how to make it possible that way.
Thank you before!

In your if statements you are assigning values, not checking. To check use double or triple equal signs (==) or (===)
Example: if(santanVid === 'pausing')

Related

Does changing an element's inner text interferes with their children elements? (Issue with audio element)

I've got this Track component that I want to be able to play a preview audio from.
const Track = props => {
const handlePreview = e => {
if (!props.track.preview) {
e.target.innerText = 'No preview available';
return;
}
e.target.children[0].paused
? e.target.children[0].play()
: e.target.children[0].pause();
}
return (
<div className='preview' onClick={handlePreview}>
Preview
<audio src={props.track.preview}>Audio not supported</audio>
</div>
)
I want to be able to switch the inner text of the div between 'Preview' and 'Click to pause' depending on whether the preview is playing or not. For some reason, if I add the code to do that, the play and pause methods stop working. I tried using ref instead of "e.target.children[0]" but it doesn't work properly either (the first time I click, nothing happens, but after that, it plays and pauses with every click).
I can't tell what's wrong. Help?

Media play/pause toggling without using too many if statements?

I am creating a playlist of songs for a website that looks like this:
However, I am struggling to figure out the proper way to implement all of the possible case statements that a user may go through while toggling the buttons such as:
toggling one play button on and off
toggling one play button on, and then clicking another play button so that the previous has to toggle off
and so on.
Right now my code (below) works for every case EXCEPT for when a user toggles a play button on and off, and then clicks a different play button. This specific case causes both of the icons to toggle to the pause button instead of just the most recently clicked. I know why this happens, it is because an ID of lastPlayed is left on the old play button, thus triggering the toggle if statment.
My question is, is there an easier way to set up play button toggling that covers all of these cases without having to make a specific if statement for every possible outcome?
Either finding a better solution or fixing my one bug works, but cleaner code is always preferred, thanks for any help!
var playCounter = 0;
function clickSongPlay(artist, title, url, imageURL, element) {
//debugger;
player.playlist.push(
{
title: title,
artist: artist,
file: url,
imageURL: imageURL,
howl: null
}
);
//check to see if we need to resume the song
if ($(element).hasClass("resumeSong") && $(".music-control").hasClass("ion-ios-play")) {
console.log("resuming");
/////////LINE BELOW RESUMES THE TRACK FROM CURRENT POSITION////////
player.play();
$(element).toggleClass("ion-ios-play ion-ios-pause");
$(".resumeSong").removeClass("resumeSong");
return;
}
//if a song is playing and the pause button is clicked, pause the track
if ($(element).hasClass("ion-ios-pause")) {
console.log("pausing");
player.pause();
$(element).toggleClass("ion-ios-pause ion-ios-play");
$(element).addClass("resumeSong");
return;
}
//start playing a new song
if ($(element).hasClass("ion-ios-play") && !$(element).hasClass("resumeSong")) {
if ($("#lastPlayed") && !playCounter == 0) {
console.log("here is a new song");
$("#lastPlayed").toggleClass("ion-ios-pause ion-ios-play")
$(".music-control").removeAttr("id", "lastPlayed");
}
console.log("new song");
///////LINE BELOW LOADS THE NEW SONG//////////////
player.skipTo(player.playlist.length - 1);
$(element).toggleClass("ion-ios-play ion-ios-pause");
$(element).attr("id", "lastPlayed");
playCounter += 1;
return;
}
}
Here is the HTML for a specific song div:
<div><i class="icon ion-ios-play music-control" onclick="clickSongPlay('#song.Artist','#song.Title','#song.URL','#song.Album.ImageURL', this);"></i></div>
Well, as I can see it, there are two problems here.
One, you need to pause any song that is currently playing, whenever an element is clicked. The step that is missing from your code is the position at which we the playing song is advanced so far. I'd record this into a data-offset property of the element itself. So later, we can continue playback from where it left...
Two, find out if the clicked element is on pause or not. If it is - resume, else play from the beginning.
So here is UNTESTED code sample, which might set you on the right track:
function clickSongPlay(artist, title, url, imageURL, element) {
var nowPlaying = $(element).siblings(".ion-ios-pause")
if (nowPlaying) {
player.pause();
nowPlaying.data("offset") = player.seek();
nowPlaying.toggleClass("ion-ios-pause ion-ios-play");
nowPlaying.addClass("resumeSong");
}
player.src(url);
player.seek($(element).data("offset"));
if ($(element).hasClass("resumeSong")) {
console.log("resuming");
$(element).removeData("offset");
$(element).toggleClass("ion-ios-play ion-ios-pause");
$(element).removeClass("resumeSong");
}
player.play();
}

Javascript Sound Start/Stop and Image Change Part2

I want to have a small image that when clicked plays a sound and changes to a different image. When the button is then clicked again it changes back to previous image ans stops the sound.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I tried using this code and it works perfectly for the images, but i can not seem to get the different sounds to play for the 2 images.
Javascript Sound Start/Stop and Image Change
I also found seperate code to play and stop sound with this script:
<script>
$(document).ready(function() {
var playing = false;
$('a#button').click(function() {
$(this).toggleClass("down");
if (playing == false) {
document.getElementById('player').play();
playing = true;
$(this).text("stop sound");
} else {
document.getElementById('player').pause();
playing = false;
$(this).text("restart sound");
}
});
});
</script>
<div>
<a id="button">play sound</a>
<audio id="player" src="mysound.mp3" preload="auto"></audio>
Which also works...
Can I combine the 2 together? Or am I not using the first javascript code correctly?
Any help would be much appreciated.
If you want to play a sound and change the image and vice versa, the following would work just fine:
HTML
<p>
<i class="fa fa-play fa-lg" aria-hidden="true"></i>
</p>
<audio id="player" src="http://soundbible.com/mp3/kids-record-player-daniel_simon.mp3" preload="auto"></audio>
JS
var playing = false;
$('#button').click(function() {
if (playing == false) {
document.getElementById('player').play();
playing = true;
$(this).find('i').removeClass('fa-play');
$(this).find('i').addClass('fa-pause');
} else {
document.getElementById('player').pause();
playing = false;
$(this).find('i').removeClass('fa-pause');
$(this).find('i').addClass('fa-play');
}
});
The idea is basically this: If the sound is playing, then swap classes. This example could be expanded to toggling the hide and show of images.
Refer to this working example.
Hope it helps.
EDIT
f I would want to use this for more than one image on the same webpage. Do I just add more add & remove classes? Or do I make a new function for every image?
Actually you can use that function for any number of images. We just need to generalize a few things and we are good to go.
The first thing I did was to change the jQuery selector for the click event. Previously we searched specifically for the element with the unique id #button. In order to bind to multiple buttons, I gave them the same name: $('[name=button]').
The variable playing helped us keep track whether or not the user played the button. In order to control whether or not the button was clicked, I had to move the variable playing to the audio element as an attribute. This way every audio element "knows" its current state (playing or paused);
HTML
<audio name="player" src="http://soundbible.com/mp3/kids-record-player-daniel_simon.mp3" preload="auto" data-playing="false"></audio>
Notice the data-playing="false" attribute
JS
var $button = $(this), // get the button
$player = $button.next('[name=player]'); // button and player are siblings
if ($player.data('playing') == false) {
$player[0].play();
$player.data('playing', true);
...
} else {
$player[0].pause();
$player.data('playing', false);
...
}
The trick here is to update the playing attribute to ensure we know the user clicked play or pause
Please refer to this updated version of the previous example.

How to hide an element on click instead of timeout using Clippy.js?

I found a neat little JS library called Clippy.js that lets you implement Microsoft Word's old virtual assistants in your browser. After playing around with it for a while I realized that the text balloon has a setTimeout() method and a time delay causing it to disappear.
hide:function (fast) {
if (fast) {
this._balloon.hide();
return;
}
this._hiding = window.setTimeout($.proxy(this._finishHideBalloon, this), this.CLOSE_BALLOON_DELAY);
},
_finishHideBalloon:function () {
if (this._active) return;
this._balloon.hide();
this._hidden = true;
this._hiding = null;
},
I don't want that. I want the balloon to disappear when a user clicks. I tried registering an event listener by replacing this._hiding = ... with this:
var clickToHide = document.getElementsByClassName('clippy-balloon');
this._hiding = clickToHide.addEventListener('click', function(){$.proxy(this._finishHideBalloon, this)});
...but all that it does is hide the balloon completely. Why does that not work? And how do I achieve the functionality I want?
I think the delay is caused by the variable CLOSE_BALLOON_DELAY.
Changing this.CLOSE_BALLOON_DELAY to 0 should do the trick.

Not returning focus to browser after alert pop-up

I am trying to do a little pacman game to train my JavaScript skills. To move pacman around, I use the onkeyup event function associated with a move function.
Still I am having a problem. Every time pacman dies (or game ends) I always use an alert box to alert the user of what happened. Still, after I press the OK button to make pacman move again I must click on the browser window to make it responsive to keyboard events.
Somehow I believe this is a windows focus problem, still, tried to use some focus around (after the alert box mainly) and doesn't seem to do the trick.
Can someone give me general pointers of what could be the solution for this?
PS: In the game construction I am using images created on the fly, having only 2 text tags on the page with id's.
EDIT: code associated in the onkeyup:
function muda_sentido(event)
{
//baixo
if(event.keyCode == 40)
{
pacman_status = status[2];
imagem_pacman.src = "Imagens/pacmanb.gif";
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmanb.gif";
}
//direita
else if(event.keyCode == 39)
{
pacman_status = status[0];
imagem_pacman.src = "Imagens/pacmand.gif";
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmand.gif";
}
//cima
else if(event.keyCode == 38)
{
pacman_status = status[3];
imagem_pacman.src = "Imagens/pacmanc.gif";
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmanc.gif";
}
//esquerda
else if(event.keyCode == 37)
{
pacman_status = status[1];
imagem_pacman.src="Imagens/pacmane.gif"
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmane.gif";
}
}
html body contents is a double h2 tag (cannot add it to code format cause it appears messed up on the previewer) with an ID each.
And around the program I have something like:
alert("Pacman died!")
And the problem is after this.
2 EDIT: Managed to grab the piece of code that lies the alert box (just changed it now to look for it in only one place):
function pacman_morreu()
{
alert("O pacman morreu!");
if(pacman_vidas==0)
{
alert("Game Over!");
reinicia_tabuleiro();
}
else
{
pacman_vidas--;
vidas.innerHTML = "Número de vidas: "+ pacman_vidas;
}
pintaEcra();
}
The functions listed inside the code will only do matrix manipulation operations (nothing special really).
EDIT 3: As requested, here goes:
function reinicia_tabuleiro()
{
pacman_vidas = 3;
vidas.innerHTML = "Número de vidas: 3";
pontuacao.innerHTML = "Pontuação: 0";
pontos = 0;
for(i=1;i<24;i++)
{
for(j=1;j<24;j++)
{
if(tabuleiro[i][j] == 0)
tabuleiro[i][j] = 2;
}
}
}
Sorry dude, I don't see anything that would be causing this. What browser are you using? I'm doing similar tests on IE and FF and am getting window focus after clicking 'Ok' in the alert box. Have you tried using Firebug? It is a great program for debugging javascript. I would highly recommend it for this pacman project you are doing. You might have an error somewhere in your code that is causing this that isn't very apparent in the code shown above.
Well right now, I don't have solution to this problem but I have a workaround.
Dont use alertbox, use lightbox(div with higher z-index value) and make the div show and hide based on condition in javascript.
I hope this will help.
I just went through a similar problem with keydown and Firefox 5.0. The window focuses when the page loads and all my $(window).keydown(...) events worked fine.
Then after I show an alert, none of the events fire. It ends up that the window does not focus itself after I dismiss the alert. I was able to solve it by forcing the window to refocus when it blurs. I'm using jQuery so here's what it looks like for me:
$(window).blur(function(){
setTimeout(function(){
$(window).focus();
}, 0);
});
The timeout is necessary since Firefox (& maybe other browsers) won't let you immediately focus during a blur event.
This may have unintended consequences since you're basically never letting the window blur. For example, clicking on the location bar won't even work because the window pulls focus back immediately. To dig a deeper hole, you might set a "refocus" flag for your callback so it knows whether to give up focus or not. Here's the basic idea:
var doRefocusWindow = false;
$(window).blur(function(){
if(!doRefocusWindow) return;
doRefocusWindow = false;
setTimeout(function(){
$(window).focus();
}, 0);
});
...
doRefocusWindow = true;
alert("Game Over");

Categories

Resources