On Iframe embed click show a div or counter start - javascript

I am trying to show or start count when I click on a youtube embed Iframe .
Here is my code
<iframe id="startcount" width="900" height="400" src="https://www.youtube.com/embed/qAM8wEHPccU" frameborder="0" allowfullscreen></iframe>
<span align="center" style="color:#0091bf; font-weight:bold; font-size:24px;">You will be redirected in
<span id="counter">30</span> second(s) for credit verification. </span>
<script type="text/javascript">
$(document).ready(
function() {
$("#startcount").click(function() {
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
//location.href = 'earn_credit_ac.php?ads_id=<?php echo $del_id; ?>';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
});
});
</script>
Click on youtube embeded video iframe
start counting
help me I am new in jquery .
Thanks to All

If you are counting down then you should check if the value is greater than 0, not less than 0.
The following code should work:
$(document).ready(function() {
$("#startcount").click(function() {
function countdown() {
var i = $("#counter");
var value = parseInt(i.html());
var interval;
if (value >= 0) { // I think you want "greater equal" (>=) instead of "less equal" (<=)
//location.href = 'earn_credit_ac.php?ads_id=<?php echo $del_id; ?>';
}
else {
clearInterval(interval); // stop interval if counted to -1
}
i.html(value - 1);
}
setInterval(countdown, 1000);
});
});

I am using another method to complete this task.
Html :
<button id="play-button" class="btn mobile-full" style="padding:10px;"> Play </button>
<iframe id="video" src="//www.youtube.com/embed/NV16WtEXP6E?autohide=2&border=0&wmode=opaque&enablejsapi=1&modestbranding=1&controls=0&showinfo=1&rel=0" frameborder="0" allowfullscreen></iframe>
<div align="center">
<span align="center" style="color:#0091bf; font-weight:bold; font-size:24px;">You will be redirected in
<span id="counter"><?php echo $vid_duration; ?></span> second(s) for credit verification. </span>
</div>
Css :
.button {
width: 48px;
height: 48px;
cursor: pointer;
&:hover {
fill: white;
}
}
.defs {
position: absolute;
top: -9999px;
left: -9999px;
}
iframe {
float: left;
width: 300px;
height: 200px;
}
.buttons {
padding: 1rem;
background: #f06d06;
float: left;
}
JavaScript :
<script>
// https://developers.google.com/youtube/iframe_api_reference
// global variable for the player
var player;
// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
// create the global player from the specific iframe (#video)
player = new YT.Player('video', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
// bind events
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function() {
player.playVideo();
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
location.href = 'earn_credit_ac.php?ads_id=<?php echo $del_id; ?>';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
});
}
// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
This is the only way to play youtube video on mobile and same time start the time counter .
Thanks to all .

Related

Play multiple audio tracks sequentially, not simultaneously

I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But now they play at the same time, can I somehow make them play sequentially?
<audio id="audio1" preload="" autoplay="" loop="" type="audio/mp3" src="music/mus1.mp3"></audio>
<audio id="audio2" preload="" autoplay="" loop="" type="audio/mp3" src="music/mus.mp3"></audio>
<div id="pp" style="cursor: pointer;" onclick="pVid();"><img src="img/heart.png"></div>
<script type="text/javascript">
function pVid() {
var audio1 = document.getElementById("audio1");
var audio2 = document.getElementById("audio2");
audio1.paused ? audio1.play() : audio1.pause();
audio2.paused ? audio2.play() : audio2.pause();
}
</script>
I found one solution, it works but not the way I want
var sounds = new Array(new Audio("music/mus1.mp3"), new Audio("music/mus.mp3"));
var i = -1;
pVid();
function pVid() {
i++;
if (i == sounds.length) return;
sounds[i].addEventListener('ended', pVid);
sounds[i].play();
}
Here everything just plays right away, but I want to be able to play the tracks myself through the button and pause at any time. This is done in the first version, but there all the tracks play at the same time
Use audio events as much as possible. We can use freesound.org for testing.
let sounds = new Array(new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"), new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"));
let current = random(0);
let paused = true;
// set event handlers on all audio objects
for (let s of sounds) {
s.addEventListener('ended', ended);
s.addEventListener('play', play);
s.addEventListener('pause', pause);
}
updateVolume()
// handle button click
function playPause() {
if (paused) {
sounds[current].play();
btn.innerText = 'pause';
paused = false;
} else {
sounds[current].pause();
btn.innerText = 'play';
paused = true;
}
}
function ended(e) {
document.getElementById(current + '').classList.remove('playing');
document.getElementById(current + '').classList.remove('paused');
/*i++;
if (i >= sounds.length) //loop
i = 0;
*/
current = random(current); // shuffle
paused = true;
playPause();
}
function play() {
document.getElementById(current + '').classList.add('playing');
document.getElementById(current + '').classList.remove('paused');
}
function pause() {
document.getElementById(current + '').classList.add('paused');
document.getElementById(current + '').classList.remove('playing');
}
function random(i) {
let next = i;
while (next == i)
next = Math.floor(Math.random() * sounds.length);
return next;
}
function updateVolume() {
for (let s of sounds) {
s.volume = volume.value;
}
}
#list {
margin-top: 1rem;
border: 1px solid gray;
width: 100px;
}
#controls {
position: fixed;
right: 2rem;
top: 1rem;
width: 50px;
}
#volume {
width: 150px;
height: 20px;
transform-origin: 75px 75px;
transform: rotate(-90deg) translateY(50%);
}
.playing {
background-color: lightblue;
}
.paused {
background-color: wheat;
}
<Button id=btn onClick='playPause()'>play</Button>
<div id=list>
<div id='0'>Guitar</div>
<div id='1'>Drum</div>
<div id='2'>Violin</div>
<div id='3'>Guitar</div>
<div id='4'>Drum</div>
<div id='5'>Violin</div>
</div>
<div id=controls>
<label for="volume">Volume</label><br>
<input id=volume type="range" id="volume" name="volume" min="0" max="1" step='.1' value='.5' onInput='updateVolume()'>
</div>
I don't know why no one mentioned the onended event
<audio id="aud1" onended="playaud2()" src="whatever.mp3"> <!--first audio-->
<audio id="aud2" src="whatever.mp3"> <!--second audio-->
<script>
//the onended event calls a function when the audio finishes playing
function playaud2() {
document.getElementById("aud2").play()}
</script>
As simple :)
Audio files
For testing, I used a few free sound-effects audio files from https://www.freesoundeffects.com.
To make it work in all browsers it is recommended by w3c to use the <audio>-tag with <source> tags.
Solution
I added some arbitrary sound files and buttons. The buttons will reset all the audios that are currently playing then play the sounds in the data-track attributes.
data-track syntax:
track-a // will play track a
track-a;track-b // will play track a followed by track b
track-a+track-b // will play track a and b simultaniously
track-a+track-b;track-c // as above but add track c to the end
You could do something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
audio {
display: block;
}
</style>
<script defer type="application/javascript">
let activeTimeout;
function init(player) {
player.innerHTML = `play ${player.dataset.label}`;
player.addEventListener('click', clickHandler);
}
function reset(audio) {
clearTimeout(activeTimeout);
audio.pause();
audio.currentTime = 0;
}
function dequeue(tracks) {
console.log("Queue:", tracks);
if (tracks.length >= 1) {
const track = tracks.pop();
const multiTrack = track.split('+');
let maxDuration = 0;
multiTrack.forEach((it) => {
const audio = document.querySelector(`[data-audio="${it}"]`);
maxDuration = Math.max(maxDuration, audio.duration);
audio.play();
});
activeTimeout = setTimeout(() => {
dequeue(tracks);
}, maxDuration * 1000);
}
}
function clickHandler(e) {
const allAudios = document.querySelectorAll('[data-audio]');
const trackAttr = this.dataset.track;
const tracks = trackAttr.split(';');
if (tracks) {
allAudios.forEach(reset);
dequeue(tracks.reverse()); // reverse to make the pop-operations faster
} else {
console.log('No track defined!');
}
}
window.addEventListener('load', function() {
const players = document.querySelectorAll('[data-player]');
players.forEach((it) => init(it));
});
</script>
</head>
<body>
<audio data-audio="applause" controls="controls" preload="preload">
<source src="https://www.freesoundeffects.com/files/mp3_426807.mp3" type="audio/mp3"></source><!-- replace with your audio file -->
</audio>
<audio data-audio="bark" controls="controls" preload="preload">
<source src="https://www.freesoundeffects.com/files/mp3_89478.mp3" type="audio/mp3"></source><!-- replace with your audio file -->
</audio>
<audio data-audio="chirp" controls="controls" preload="preload">
<source src="https://www.freesoundeffects.com/files/mp3_89489.mp3" type="audio/mp3"></source><!-- replace with your audio file -->
</audio>
<button data-player data-label="bark!" data-track="bark" />
<button data-player data-label="chirp!" data-track="chirp" />
<button data-player data-label="applause!" data-track="applause" />
<button data-player data-label="applause then bark!" data-track="applause;bark" />
<button data-player data-label="bark then chirp then bark again!" data-track="bark;chirp;bark" />
<button data-player data-label="applause then chirp!" data-track="applause;chirp" />
<button data-player data-label="applause with chirp then bark!" data-track="applause+chirp;bark" />
</body>
</html>
Yes, you can check if you have an element with a simple truthy/falsy check:
if (!slider) return;

How jump ahead in audio by the amount clicked on a progress bar? [duplicate]

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var counter = 0;
var numOfTracks = $(".audio-player").length;
$("#play-bt").click(function(){
$(".audio-player")[counter].play();
$("#message").text("Music started");
})
$("#pause-bt").click(function(){
$(".audio-player")[counter].pause();
$("#message").text("Music paused");
})
$("#stop-bt").click(function(){
$(".audio-player")[counter].pause();
$(".audio-player")[counter].currentTime = 0;
$("#message").text("Music Stopped");
})
$("#next-bt").click(function(){
$(".audio-player")[counter].pause();
$(".audio-player")[counter].currentTime = 0;
counter++;
if(counter > numOfTracks - 1){
counter = 0 ;
}
$(".audio-player")[counter].play();
$("#message").text("Next Track started");
})
$("#prev-bt").click(function(){
$(".audio-player")[counter].pause();
$(".audio-player")[counter].currentTime = 0;
counter--;
$(".audio-player")[counter].play();
$("#message").text("Previous Track");
})
$(".audio-player").bind('timeupdate', function(){
//Gets the whole duration of the track.
//No idea kung saan ko ilalagay sa UI**IMPLEMENT LATER**
var track_length = $(".audio-player")[counter].duration;
var secs = $(".audio-player")[counter].currentTime;
var progress = (secs/track_length) * 100;
$('#progressbar').css({'width' : progress * 2});
//Will Use these later on production
//NOTE DO NOT DELETE
//Track Minutes
var tcMins = parseInt(secs/60);
//Track Seconds
var tcSecs = parseInt(secs - (tcMins * 60));
if (tcSecs < 10) { tcSecs = '0' + tcSecs; }
// Display the time. REMEMBER
$('#timecode').html(tcMins + ':' + tcSecs);
})
})
</script>
<style>
/*Seperate this some time in the development*/
#playerContainer{
background-color: #A8A8A8 ;
width: 260px;
height: 55px;
padding: 8px;
border: 1px solid #d0d0d0;
}
/* Player Controls */
/*list items of controls */
#playerControls li {
display: block;
width: 32px;
height: 32px;
padding: 0px;
float: left;
cursor: pointer;
}
#playerControls { list-style: none; padding: 0px; margin: 0px;}
/*Images for each li items items */
#play-bt { background: url('icons/glyphicons_173_play.png'); background-repeat:no-repeat }
#pause-bt {background: url('icons/glyphicons_174_pause.png'); background-repeat:no-repeat;}
#next-bt { background: url('icons/glyphicons_176_forward.png'); background-repeat:no-repeat}
#prev-bt {background: url('icons/glyphicons_172_rewind.png'); background-repeat:no-repeat;}
/*Progress Stuff*/
/*Remember to manipulate its width via javascript later*/
#progressContainer
{
background-color:#e0e0e0;
height: 14px;
width: 256px;
float: left;
margin-left: 0px;
}
#progressbar {background-color: #1384bb; height:14px; width:0%; }
</style>
</head>
<body>
<audio class ="audio-player" name= "audio-player" src="04-zedd-stars_come_out_(terravita_remix).ogg" >
<p>Sorry your file doesn't support html5</p>
</audio>
<!--Second Track For Testing Purposes-->
<audio class ="audio-player" name= "audio-player" src="01-hard_rock_sofa-quasar.mp3" ></audio>
<div id="message"></div>
<div id = "playerContainer">
<ul id = "playerControls" >
<li id = "prev-bt"></li>
<li id= "play-bt"></li>
<li id= "pause-bt"></li>
<li id = "next-bt"></li>
<li id= "stop-bt" ></li>
<li><span id ="timecode"></span></li>
</ul>
<div id="progressContainer"><!-- Progess bars container //-->
<div id="progressbar"></div>
</div>
</div>
</div>
</body>
</html>
How can I click a certain part of my progress bar so that I can move it to a different time in the track? I have no idea on how I am going to do that. any ideas ?
Given some html that looks like this:
<div class="container">
<video class="video">
<source></source>
</video>
<progress min="0" max="100" value="0"></progress>
<div class="controls"></div>
</div>
In order to seek to a specific time in the video as a result of a click event the js would look like this:
var player = document.querySelector("video");
var progressBar = document.querySelector("progress");
progressBar.addEventListener("click", seek);
function seek(e) {
var percent = e.offsetX / this.offsetWidth;
player.currentTime = percent * player.duration;
progressBar.value = percent / 100;
}
However, this doesn't address how to seek on a click/drag (like most video players do). include script
I came across this question today because I am creating a custom HTML5 video player and had the same question. Just in regards to video instead of audio. The process should work the same though.
I found this article and was able to incorporate the progress bar part of it into my player. https://msdn.microsoft.com/en-us/library/ie/gg589528%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
Instead of using a progressbar element, like I was doing, or a div element, like you're doing, the trick here is to use a canvas element instead.
<canvas id='progress-bar' width="200" height="20" style="border:1px solid green;">canvas not supported</canvas>
Then in your JavaScript, create a handle to reference it by
var mediaPlayer;
var progressBar;
var canvas;
When the document loads, initialize everything including the progress bar items
mediaPlayer = document.getElementById('media-video');
progressBar = document.getElementById('progress-bar');
canvas = document.getElementById('progress-bar');
canvas.addEventListener("click", function(e) {
var canvas = document.getElementById('progress-bar');
if (!e) {
e = window.event;
} //get the latest windows event if it isn't set
try {
//calculate the current time based on position of mouse cursor in canvas box
mediaPlayer.currentTime = mediaPlayer.duration * (e.offsetX / canvas.clientWidth);
}
catch (err) {
// Fail silently but show in F12 developer tools console
if (window.console && console.error("Error:" + err));
}
}, true);
mediaPlayer.addEventListener('timeupdate', updateProgressBar, false);
Then create a function outside of your initialization function for the timeupdate listener to call and automatically update the progress bar for you
function updateProgressBar() {
mediaPlayer = document.getElementById('media-video');
//get current time in seconds
var elapsedTime = Math.round(mediaPlayer.currentTime);
//update the progress bar
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
//clear canvas before painting
ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
ctx.fillStyle = "rgb(255,0,0)";
var fWidth = (elapsedTime / mediaPlayer.duration) * (canvas.clientWidth);
if (fWidth > 0) {
ctx.fillRect(0, 0, fWidth, canvas.clientHeight);
}
}
}
I haven't completely cleaned it up yet. Hence the redundant handles to the same id. But I'm sure you get the picture.
Hope this can save someone some time. If you're trying to set this up in an Angular app, you'll notice this is your controller context. So you'll need to use e.srcElement.clientWidth for this to work.
vm.setPosition = function(e){
var percent = ((e.offsetX / e.srcElement.clientWidth));
vm.songObject.setProgress(percent);
}
I wrote about that in Working with HTML5 multimedia components – Part 3: Custom controls, scroll down to "Adding a progress bar".

Building a jquery/javascript HIIT with autoplay video or image slider "playlist" using and php/mysql

I am trying to create a countdown timer with videos. The timer needs to load data such as time for countdown, time for breaks, and number of sets the timers needs to run, video(or images in case of no video) from a MySQL table.
The timer starts counting down but needs also to start auto-playing video of image slider. When time ends starts counting down for the time break. This process continues till number of sets reached. Then it is needed to either click to go to the next countdown or after a short countdown break to load the next in queue.
I can load the data from MySQL with php and create a while loop to pass the variables need in the jQuery/JavaScript script. But i am not sure if this is the right way.
This is my approach with a bug related on clicking start/stop/reset buttons which leads to an increase of speed during countdown, and in some unwanted results regarding counting down.
A fix on that bug would be appreciated.
My code:
var startTime = 10;
var restTime = 5;
var currentTime = 0;
var myTimer;
var myTimerSpeed = 1000; // 1 sec
var currentSet = 0;
var currentPause = 0;
var totalSets = 5;
resetTimer();
restTimer();
$('#pause').hide();
$('#next_exe').hide();
$('#player').show();
$('input[value="start"]').click(startTimer);
$('input[value="stop"]').click(stopTimer);
$('input[value="reset"]').click(resetTimer);
$('#currentset').html(currentSet);
$('#totalset').html(totalSets);
$('#currentpause').html(currentPause);
$('#totalpause').html(totalSets);
function resetTimer() {
stopTimer();
currentTime = startTime;
$('#timer').html(currentTime);
}
function startTimer() {
currentSet++;
if (currentTime <= 0) {
//resetTimer();
startTimer();
} else {
myTimer = setInterval(timerTick, myTimerSpeed);
}
$('#currentset').html(currentSet);
}
function restTimer() {
stopTimer();
currentTime = restTime;
$('#timer').html(currentTime);
}
function breakTimer() {
currentPause++;
if (currentTime <= 0) {
restTimer();
breakTimer();
} else {
myTimer = setInterval(timerTick, myTimerSpeed);
}
$('#currentpause').html(currentPause);
}
function timerTick() {
currentTime--;
if (currentTime == 0 && currentSet == totalSets) {
if (currentPause < totalSets && currentPause < currentSet) {
restTimer();
breakTimer();
$('#pause').show();
$('#player').hide();
$('#next_exe').hide();
} else {
stopTimer();
//$('#myTimer').hide();
$('#next_exe').show();
$('#pause').hide();
$('#player').hide();
}
} else if (currentTime == 0 && currentSet < totalSets) {
if (currentPause < totalSets && currentPause < currentSet) {
restTimer();
breakTimer();
$('#pause').show();
$('#player').hide();
} else {
resetTimer();
startTimer();
$('#pause').hide();
$('#player').show();
}
}
$('#timer').html(currentTime);
$('#currentset').html(currentSet);
$('#currentpause').html(currentPause);
}
function stopTimer() {
clearInterval(myTimer);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
I want to create 2 countdowns, which can loop everytime countdown ends and a set is completed.
</p>
<div id="myTimer" style="background-color:#eee; clear:both; display:block; float:left; height:250px; width:300px; margin:0; padding:20px;">
<div id="player" style="background-color:#333; color:#fff; font-size:14pt; clear:both; display:block; float:left; height:150px; width:300px; margin:0; padding:0;">
<!-- embed for youtube video https://www.youtube.com/watch?v=NlOF03DUoWc -->
<iframe width="100%" height="150" src="http://www.youtube.com/embed/gmRTQfLrbMY" frameborder="0" allowfullscreen></iframe>
</div>
<div id="pause" style="background-color:#333; color:#fff; font-size:14pt; clear:both; display:block; float:left; height:50px; width:300px; margin:0; padding:50px 0;">
PAUSE
</div>
<div id="next_exe" style="background-color:#333; color:#fff; font-size:14pt; clear:both; display:block; float:left; height:50px; width:300px; margin:0; padding:50px 0;">
Next Exercise
</div>
<p id='timer'></p>
<input type="button" value="stop">
<input type="button" value="start">
<input type="button" value="reset">
</div>
<div id="sets" style="background-color:#eee; clear:both; display:block; float:left; height:50px; width:300px; margin:10px 0 0; padding:20px;">
Number of Sets completed: <span id="currentset"></span> / <span id="totalset"></span>
<br> Number of Breaks completed: <span id="currentpause"></span> / <span id="totalpause"></span>
</div>
Also available on JSfiddle
Suggestion of a friend:
$('#pause').hide();
$('#player').hide();
$('#next_exe').hide();
function Timer(speed, duration, onTick, onComplete) {
var speed = speed;
var interval = null;
var current = duration;
var onTick = (typeof onTick == 'function') ? onTick : function() {}
var onComplete = (typeof onComplete == 'function') ? onComplete : function() {}
function decrement() {
onTick(current);
if (current > 0) {
current -= 1;
} else {
stop();
onComplete();
}
}
function start() {
if (!interval) {
interval = window.setInterval(decrement, speed);
}
}
function stop() {
if (interval) {
interval = window.clearInterval(interval);
}
}
function reset() {
current = duration;
onTick(current);
}
return {
start: start,
stop: stop,
reset: reset
};
}
function RoundCounter() {
var currentSet = 0;
var totalSets = 2;
var currentPause = 0;
var totalPause = 2;
var currentTimer = null;
var mode = null;
function initialize() {
mode = "set";
currentTimer = Timer(1000, 10, timerTick, completeSet);
setupUI();
bindUIEvents();
}
function setupUI() {
$('#totalset').html(totalSets);
$('#totalpause').html(totalPause);
$('#currentset').html(currentSet);
$('#currentpause').html(currentPause);
}
function bindUIEvents() {
$('input[value="start"]').click(function() {
runTimer(currentTimer);
$('#pause').hide();
$('#player').show();
$('#next_exe').hide();
});
$('input[value="stop"]').click(function() {
stopTimer(currentTimer);
});
$('input[value="reset"]').click(function() {
resetTimer(currentTimer);
});
$('#sets')
.on("timerset.complete", function() {
updateUI();
})
.on("timerpause.complete", function() {
updateUI();
});
}
function updateUI() {
$('#currentset').html(currentSet);
$('#currentpause').html(currentPause);
if (currentPause == totalPause &&
currentSet == totalSets) {
endRound();
return;
}
if (mode == "set") {
$('#pause').hide();
$('#player').show();
$('#next_exe').hide();
if (currentPause < totalPause) {
currentTimer = Timer(1000, 5, timerTick, completePause);
runTimer(currentTimer);
}
mode = "pause";
} else if (mode == "pause") {
$('#pause').show();
$('#player').hide();
$('#next_exe').hide();
if (currentSet < totalSets) {
currentTimer = Timer(1000, 10, timerTick, completeSet);
runTimer(currentTimer);
}
mode = "set";
}
}
function startNextTimer() {
if (mode == "set") {}
}
function timerTick(currentTime) {
$('#timer').html(currentTime);
}
function runTimer(timer) {
timer.start();
}
function stopTimer(timer) {
timer.stop();
}
function resetTimer(timer) {
timer.reset();
}
function completeSet() {
currentSet += 1;
$("#sets").trigger("timerset.complete");
$('#pause').show();
$('#player').hide();
$('#next_exe').hide();
}
function completePause() {
currentPause += 1;
$("#sets").trigger("timerpause.complete");
$('#pause').hide();
$('#player').show();
$('#next_exe').hide();
}
function endRound() {
$('#myTimer').hide();
$('#sets')
.off('timerset.complete')
.off('timerpause.complete');
}
return {
initialize: initialize
};
}
// on document ready, initialize everything
$(function() {
RoundCounter().initialize();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
I want to create 2 countdowns, which can alter everytime countdown ends and a set is completed.
</p>
<div id="myTimer" style="background-color:#eee; clear:both; display:block; float:left; height:auto; width:300px; margin:0; padding:20px;">
<div id="player" style="background-color:#333; color:#fff; font-size:12pt; clear:both; display:block; float:left; height:180px; width:300px; margin:0 0 20px; padding:0;">
<!-- embed for youtube video https://www.youtube.com/watch?v=NlOF03DUoWc -->
<iframe width="100%" height="150" src="http://www.youtube.com/embed/gmRTQfLrbMY" frameborder="0" allowfullscreen></iframe> VIDEO or Image Slider
</div>
<div id="pause" style="background-color:#333; color:#fff; font-size:12pt; clear:both; display:block; float:left; height:80px; width:280px; margin:0 0 20px; padding:50px 10px;">
PAUSE
</div>
<div id="next_exe" style="background-color:#333; color:#fff; font-size:12pt; clear:both; display:block; float:left; height:80px; width:280px; margin:0 0 20px; padding:50px 10px;">
go to next exercise
</div>
<p id='timer'></p>
<input type="button" value="stop">
<input type="button" value="start">
<input type="button" value="reset">
</div>
<div id="sets" style="background-color:#eee; clear:both; display:block; float:left; height:50px; width:300px; margin:10px 0 0; padding:20px;">
Number of Sets completed: <span id="currentset"></span> / <span id="totalset"></span>
<br> Number of Breaks completed: <span id="currentpause"></span> / <span id="totalpause"></span>
</div>
This is also available on JSfiddle
Your timer issue comes from these lines of code:
myTimer = setInterval(timerTick, myTimerSpeed);
An interval is not really a variable, when you call setInterval you are creating an interval and getting in return a reference to that interval.
So if the code above is called twice, you'll have 2 intervals running but only a reference to the 2nd one, which means it will run forever and you no longer have the value needed to stop the first one.
What your friend did is to ensure there was no running interval referenced by his variable before starting a new one.
You can achieve the same result by replacing the lines above with:
if(myTimer) clearInterval(myTimer);
myTimer = setInterval(timerTick, myTimerSpeed);
And adding an initial value to your timer with var myTimer = false;. That should fix your timer issues
To fix transitions, I basically removed their logic from the timers start/stop functions. All transitions are now handled by timerTick().
I added a isBreak variable to remember if we're currently in a break or set, which is then used to determine what step is next and what timer initial value to fetch.
I included two reset functions in the code (resetAll() & resetCurrent()), since I didn't know if you wanted to reset everything or only the current timer.
It should now work as follow: set -> break (5x) and on the last break, instead of PAUSE it displays Next Exercise (to which you can add a click listener calling loadNext() if you want the user to be able to start it manually).
In loadNext() you can load the images for the next exercise, and if you uncomment startTimer() it will start right away.
Result: Fiddle
Does that work as you wanted it to?

I need help getting autoplay to work via [getElementById]

My code: https://jsfiddle.net/m656xw8s/24/
I've been trying to get autoplay to work, can someone show me what the correct code would be? Using the code I provided. Using [getElementById]
var player = document.getElementById('player').autoplay; document.getElementById('player').innerHTML = true;
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
var player = document.getElementById('player').autoplay;
document.getElementById('player').innerHTML = true;
var player = document.getElementById('player').volume='1.0';
var button = document.getElementById('playButton');
var player = document.getElementById('player');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>
Set the autoplay then load.
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay
Update:
document.getElementById('playButton').addEventListener('click', autoPlayToggle);
document.getElementById('autovolume_range').addEventListener('change', changeVol);
//Only getElementById once!
var player = document.getElementById("player");
var autoplaytext = document.getElementById("autoplay_text");
var autovolumetext = document.getElementById("autovolume_range");
//Boolean from localstorage to keep state of the player
var autoPlayOn = autoplaytext.value = (localStorage.getItem("keepAutoPlay") === "true");
var setVolumeOn = autovolumetext.value = parseFloat(localStorage.getItem("keepVolume"));
player.volume = setVolumeOn;
player.autoplay = autoPlayOn;
player.load();
//Force play if it dosen't autoplay after refresh
if (player.autoplay == true) {
player.play();
} else {
player.pause();
}
//Function
//When the user refreshes the page it will keep the autoplay state
function autoPlayToggle() {
if (player.paused) {
player.play();
player.autoplay = true;
} else {
player.pause();
player.autoplay = false;
}
//Show the state in a text box
autoplaytext.value = player.autoplay;
//Save updated state to your local disk
localStorage.setItem("keepAutoPlay", autoplaytext.value);
}
//Save state of volume
function changeVol() {
player.volume = this.value;
localStorage.setItem("keepVolume", this.value);
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;">
</button>
<audio id="player" style="display:none;" >
<source src='http://hi5.1980s.fm/;' type='audio/mpeg'/>
</audio>
AutoPlay: <input id="autoplay_text" />
AutoVolume: <input type="range" step="0.1" min="0.0" max="1.0" id="autovolume_range" />
https://jsfiddle.net/LeroyRon/dtnrdjd5/
You only need to add attribute auto play to your audio tag see the updated code below; Based on your code you are redeclaring player multiple times see the updated code below. Your auto play is triggered on button click based on your code, you may want to separate the javascript codes to the button and just trigger a method indicated on your button click event.
You will need to use removeAttribute to remove the autoplay from your audio element. I added the code on how to do it below.
//player declared outside of the audioPlay method to make it accessible inside the audioPlay method
var player = document.getElementById('player');
//auto play set outside playAudio method outside of the button click event method
player.setAttribute('autoplay', '');
//to set autoplay false uncomment the code below
//player.removeAttribute('autoplay');
//playAudio is triggered on button click event
function playAudio(){
player.setAttribute('volume', 1.0);
var button = document.getElementById('playButton');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
playAudio()">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>

how to expand onclick <video>

here's my html code:
echo "<div>";
echo '<video controls><source src="stuff/' . $entry . '"></video>';
echo "</div>";
here's my js code:
<script>
var videou = $( "video" ).attr("width", "150") + $( "video" ).attr("height", "80");
$( "video" ).click(function()
{
$(this).attr("width","500");
$(this).attr("height","500");
var open = true;
});
</script>
i want to go back to the original attributes. But i already tried everything. Should i use divs?
Expansion is a transitional event. Do you mean changing the width/height?
Here are expansion methods. As I had mention, check out jQuery's .slideDown() feature. Is this what you were looking for?
Simply replace the code for the .videocontainer with a video frame.
$(document).ready(function(){
$(function(){
var videos = $('.video'),
state = false;
videos.each(function(){
var videocon = $(this),
btn = videocon.find('.expandvideo'),
video = videocon.find('.videocontainer');
btn.on('click', function() {
if ( state == false ) {
video.slideDown('fast', function() { state = true; btn.html('Close Video'); });
} else {
video.slideUp('fast', function() { state = false; btn.html('Show Video'); });
}
});
});
});
});
.videocontainer {
display: none;
width: 500px;
height: 380px;
background-color:gray;
}
.expandvideo {
cursor: pointer;
color: blue;
}
.expandvideo:hover {
color: red;
}
<div class="video">
<span class="expandvideo">Show Video</span>
<div class="videocontainer">
<!-- Video Code -->
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also to expand the frame look into jQuery's .animate() function.
$(document).ready(function(){
$(function(){
var videos = $('.video'),
state = false;
videos.each(function(){
var videocon = $(this),
btn = videocon.find('.expandvideo'),
video = videocon.find('.videocontainer');
btn.on('click', function() {
if ( state == false ) {
video.animate({width: '500px', height: '500px'}, 'fast', function() { state = true; btn.html('Close Video'); });
} else {
video.animate({width: '100px', height: '80px'}, 'fast', function() { state = false; btn.html('Show Video'); });
}
});
});
});
});
.videocontainer {
width: 100px;
height: 80px;
background-color:gray;
}
.expandvideo {
cursor: pointer;
color: blue;
}
.expandvideo:hover {
color: red;
}
<div class="video">
<span class="expandvideo">Show Video</span>
<div class="videocontainer">
<!-- Video Code -->
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your question is hard to understand, but based on your js code, maybe is this what you want
<script>
var open = false;
$( "video" ).attr("width", "150");
$( "video" ).attr("height", "80");
$( "video" ).click(function()
{
if(open){
$(this).attr("width","150");
$(this).attr("height","80");
open = false;
}else{
$(this).attr("width","500");
$(this).attr("height","500");
open = true;
}
}
);
</script>
I'm not sure exactly what you are trying to achieve, as your description seems rather vague... If you are wanting a video to be displayed on the click of another element...
echo '<div id="divVideo" style="display: none;">';
echo '<video controls><source src="stuff/' . $entry . '"></video>';
echo '</div>';
echo 'Show Video';
<script>
$(document).ready(function() {
$('#aVideo').click(function(e) {
e.preventDefault();
$('#divVideo').show();
}
});
</script>
If that is not what you are trying to do, then please more descriptive and I'll try to help the best I can.

Categories