HTML5 Audio player, make pause and play on time out - javascript

How do i edit this code below so that the activeSong.Play() will only occur for 10 seconds, then it will trigger the activeSong.pause() event
I have tried to code it but i thought it would be easier to post the clean code rather than my butchered attempt
<script type="text/javascript">
var activeSong;
//Plays the song. Just pass the id of the audio element.
function play(id){
//Sets the active song to the song being played. All other functions depend on this.
activeSong = document.getElementById(id);
//Plays the song defined in the audio tag.
activeSong.play();
//Calculates the starting percentage of the song.
var percentageOfVolume = activeSong.volume / 1;
var percentageOfVolumeMeter = document.getElementById('volumeMeter').offsetWidth * percentageOfVolume;
//Fills out the volume status bar.
document.getElementById('volumeStatus').style.width = Math.round(percentageOfVolumeSlider) + "px";
}
//Pauses the active song.
function pause(){
activeSong.pause();
}
//Does a switch of the play/pause with one button.
function playPause(id){
//Sets the active song since one of the functions could be play.
activeSong = document.getElementById(id);
//Checks to see if the song is paused, if it is, play it from where it left off otherwise pause it.
if (activeSong.paused){
activeSong.play();
}else{
activeSong.pause();
}
}
//Updates the current time function so it reflects where the user is in the song.
//This function is called whenever the time is updated. This keeps the visual in sync with the actual time.
function updateTime(){
var currentSeconds = (Math.floor(activeSong.currentTime % 60) < 10 ? '0' : '') + Math.floor(activeSong.currentTime % 60);
var currentMinutes = Math.floor(activeSong.currentTime / 60);
//Sets the current song location compared to the song duration.
document.getElementById('songTime').innerHTML = currentMinutes + ":" + currentSeconds + ' / ' + Math.floor(activeSong.duration / 60) + ":" + (Math.floor(activeSong.duration % 60) < 10 ? '0' : '') + Math.floor(activeSong.duration % 60);
//Fills out the slider with the appropriate position.
var percentageOfSong = (activeSong.currentTime/activeSong.duration);
var percentageOfSlider = document.getElementById('songSlider').offsetWidth * percentageOfSong;
//Updates the track progress div.
document.getElementById('trackProgress').style.width = Math.round(percentageOfSlider) + "px";
}
function volumeUpdate(number){
//Updates the volume of the track to a certain number.
activeSong.volume = number / 100;
}
//Changes the volume up or down a specific number
function changeVolume(number, direction){
//Checks to see if the volume is at zero, if so it doesn't go any further.
if(activeSong.volume >= 0 && direction == "down"){
activeSong.volume = activeSong.volume - (number / 100);
}
//Checks to see if the volume is at one, if so it doesn't go any higher.
if(activeSong.volume <= 1 && direction == "up"){
activeSong.volume = activeSong.volume + (number / 100);
}
//Finds the percentage of the volume and sets the volume meter accordingly.
var percentageOfVolume = activeSong.volume / 1;
var percentageOfVolumeSlider = document.getElementById('volumeMeter').offsetWidth * percentageOfVolume;
document.getElementById('volumeStatus').style.width = Math.round(percentageOfVolumeSlider) + "px";
}
//Sets the location of the song based off of the percentage of the slider clicked.
function setLocation(percentage){
activeSong.currentTime = activeSong.duration * percentage;
}
/*
Gets the percentage of the click on the slider to set the song position accordingly.
Source for Object event and offset: http://website-engineering.blogspot.com/2011/04/get-x-y-coordinates-relative-to-div-on.html
*/
function setSongPosition(obj,e){
//Gets the offset from the left so it gets the exact location.
var songSliderWidth = obj.offsetWidth;
var evtobj=window.event? event : e;
clickLocation = evtobj.layerX - obj.offsetLeft;
var percentage = (clickLocation/songSliderWidth);
//Sets the song location with the percentage.
setLocation(percentage);
}
//Set's volume as a percentage of total volume based off of user click.
function setVolume(percentage){
activeSong.volume = percentage;
var percentageOfVolume = activeSong.volume / 1;
var percentageOfVolumeSlider = document.getElementById('volumeMeter').offsetWidth * percentageOfVolume;
document.getElementById('volumeStatus').style.width = Math.round(percentageOfVolumeSlider) + "px";
}
//Set's new volume id based off of the click on the volume bar.
function setNewVolume(obj,e){
var volumeSliderWidth = obj.offsetWidth;
var evtobj = window.event? event: e;
clickLocation = evtobj.layerX - obj.offsetLeft;
var percentage = (clickLocation/volumeSliderWidth);
setVolume(percentage);
}
//Stop song by setting the current time to 0 and pausing the song.
function stopSong(){
activeSong.currentTime = 0;
activeSong.pause();
}
</script>

Related

How to stop javascript from executing after clicking stop button?

<script>
function timer(duration, elementId, scoreID, mistakesID){
var start = Date.now();
var min, sec, diff;
var scoreComputed = false;
function timerCompute(){
diff = duration - (((Date.now() - start) / 1000) | 0);
min = ( diff / 60 ) | 0;
sec = ( diff % 60 ) | 0;
//If less than 10, add zero in front of it to keep tens place
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
elementId.textContent = min + ":" + sec;
if ( diff <= 0 ){
elementId.textContent = "0:00";
if (!scoreComputed){
score /= (duration / 60);
score = Math.round(score);
scoreComputed = true;
}
scoreID.textContent = score;
document.getElementById("usertext").readOnly = true;
$("#resultsContainer").fadeIn(1500);
if(mistakes.length > 0){
var mistakesStr = "";
for(var i = 0; i < mistakes.length; i++){
mistakesStr += i > 0 ? ", " : "";
usertextArr[mistakes[i]] = usertextArr[mistakes[i]] === "" ? "blank" : usertextArr[mistakes[i]];
mistakesStr += usertextArr[mistakes[i]] + " instead of " + textArr[mistakes[i]];;
}
mistakesID.textContent = mistakesStr;
$("#mistakesContainer").fadeIn(1500);
$('.type-test-wrapper').css("filter","blur(3px)");
}
return;
}
};
timerCompute();
setInterval(timerCompute, 1000);
}
var timerStarted = false;
$('#usertext').on('keydown', function() {
var time = 60 * 0.1,
display = document.querySelector('#time');
scoreDisplay = document.querySelector('#score');
mistakesDisplay = document.querySelector('#mistakes');
if ( timerStarted === false ){
timer(time, display, scoreDisplay, mistakesDisplay);
typeTest();
timerStarted = true;
}
});
</script>
The above script is from a typing test. When the typing test ends, the above script fades in a result box. I was trying to modify the code. I want to add a close button to the result box so that user can close the box after he viewed the result. So I added the below code to close the result box.
<script type='text/javascript'>
jQuery(document).ready(function($){
$('.close-btn, body').click(function(){
$('.type-test-wrapper').css("filter","blur(0px)");
$('#resultsContainer, #mistakesContainer').stop().fadeOut('medium');
});
});
</script>
The problem I am facing is that when I click on close button, the box fades out #resultContainer, #mistakesContainer but as soon the box gets faded, it again fades in. No matter how many times i close the box, it fades in again and again. I want that once user click on close button the box should not get displayed again. How to fix the code so that once the the box fades out, the first code doesn't again fades in the box. I am new at javascript. Thank you for help.
Live webpage here https://htmlpreview.github.io/?https://raw.githubusercontent.com/dp121112/type-testing/master/test.html
I think you're not clearing the interval
try to assing interval as follow.
var intrvl= setInterval(timerCompute, 1000);
and clear it when its done
scoreID.textContent = score;
document.getElementById("usertext").readOnly = true;
$("#resultsContainer").fadeIn(1500);
clearInterval(intrvl);

Modal timer progress bar

I have a modal for when a button is clicked. The modal popups and closes when the timer is up, currently 5 seconds. However, I would like to create a progress bar which shows the timer going down, no numbers just a bar that moves.
Here is what I already have: https://jsfiddle.net/cde2cup0/. YOU MUST CLICK THE BUTTON 'ADMINISTRATION' for the modal.
And here's what I want to achieve. I know my Photoshop skills aren't on point, was rushing:
The white bar at the bottom is the progress bar.
I did try this but wasn't suitable for what I needed so didn't work.
var start = new Date();
var maxTime = 835000;
var timeoutVal = Math.floor(maxTime/100);
animateUpdate();
function updateProgress(percentage) {
$('#pbar_innerdiv').css("width", percentage + "%");
$('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
var perc = Math.round((timeDiff/maxTime)*100);
if (perc <= 100) {
updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
}
Reference: jQuery progress timer bar
I don't know if correctly understood your question, but hope that helps:
Fiddle: https://jsfiddle.net/cde2cup0/2/
var progressBar = document.getElementById('myProgressBar');
function setAnimation(timeInSeconds, callbackFunction) {
var count = 0;
var interval = setInterval(function() {
if (count == timeInSeconds) {
callbackFunction();
clearInterval(interval);
}
progressBar.style.width = (100 * count / timeInSeconds) + '%';
count++;
}, 1000);
};

How to play/pause a JavaScript onClick event?

As I'm a JavaScript beginner, I wish to know how could I Play and Pause a JavaScript on an html page.
On the first JavaScript file I have a toggle button that onClick show/hide a div element tag, like this:
$(function () {
$(".toggleSidebar").click(function(event) {
$(".sidebarToggle").hide();
$(".toggleSidebar").removeClass("btn-info");
$(this).addClass("btn-info");
$("#"+$(this).attr("data-target")).fadeIn(500);
localStorage.tab_sidebar = $(this).attr("data-target")
});
if(localStorage.tab_sidebar != '')
{
$('.toggleSidebar[data-target="'+localStorage.tab_sidebar+'"]').click();
}
});
function toggleSidebar()
{
if ($("#my-section").hasClass('hide'))
$("#my-section").removeClass('hide');
else
$("#my-section").addClass('hide');
}
The div tag element has this JavaScript for the animation of the background:
var colors = new Array(
[62,35,255],
[60,255,60],
[255,35,98],
[45,175,230],
[255,0,255],
[255,128,0]);
var step = 0;
var colorIndices = [0,1,2,3];
//transition speed
var gradientSpeed = 0.0002;
function updateGradient()
{
if ( $===undefined ) return;
var c0_0 = colors[colorIndices[0]];
var c0_1 = colors[colorIndices[1]];
var c1_0 = colors[colorIndices[2]];
var c1_1 = colors[colorIndices[3]];
var istep = 1 - step;
var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
var color1 = "rgb("+r1+","+g1+","+b1+")";
var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
var color2 = "rgba("+r2+","+g2+","+b2+")";
$('#my-section').css({
background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});
step += gradientSpeed;
if ( step >= 1 )
{
step %= 1;
colorIndices[0] = colorIndices[1];
colorIndices[2] = colorIndices[3];
//pick two new target color indices
//do not pick the same as the current one
colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
}
}
setInterval(updateGradient,10);
The problem is that this JavaScript runs continuosly also when the row is hidden, wasting PC resources.
So how could I make this JavaScript goes on play (when row is shown) and pause (when row is hidden) every time I press my toggle button?
var colors = ...;
// All variable declarations for animated background
function updateGradient() {
// Update gradient function (unchanged)
}
var refreshIntervalId;
// Or var refreshIntervalId = setInterval(updateGradient, 10);
// If you want the updateGradient function to run by default when the page is open.
function toggleSidebar() {
if($("#my-section").hasClass('hide')) {
// Show sidebar
$("#my-section").removeClass('hide');
// Loops updateGradient function
refreshIntervalId = setInterval(updateGradient, 10);
} else {
// Hide sidebar
$("#my-section").addClass('hide');
// Stops updateGradient function
clearInterval(refreshIntervalId);
}
}

Javascript game - increment fires more than once

I am building simple "Spot the difference" game in jQuery/HTML. There are 5 rounds/stages, each with different pictures and user needs to go through all of them starting from round 1.
I am having this issue with increment firing twice when I am in 2nd round, and then triple times when I am in 3rd round and so on. This cause points to jump up double/triple/... instead of just jump up by 1.
The code is on baby level. I did not make any stuff to refactor it and improve.
I think I don't need to provide HTML for this, as simply looking at logic in JS file should be enough.
For those who prefer pastebin version is here (http://pastebin.com/ACqafZ5G). Full code:
(function(){
var round = 1;
var points = 0;
var pointsTotal = 0;
var pointsDisplay = $(".js-calc");
var pointsTotalDisplay = $(".js-calc-total");
var counterDisplay = $(".js-counter");
var entryPage = $(".entry-page");
var mainMenu = $(".main-menu");
var submitNow = $(".js-now");
var submitResultsFinalBtn = $(".js-submit-results-final");
// rounds-categories
var allRounds = $(".round");
var divRound1 = $(".round1"),
divRound2 = $(".round2"),
divRound3 = $(".round3"),
divRound4 = $(".round4"),
divRound5 = $(".round5");
var allPic = $(".js-pic");
var pic1 = $(".js-pic1"),
pic2 = $(".js-pic2"),
pic3 = $(".js-pic3"),
pic4 = $(".js-pic4"),
picFinish = $(".js-finish");
// on the beginning hide all and leave only entry page
mainMenu.hide();
allRounds.hide();
submitResultsFinalBtn.hide();
// countdown (SEE THE FUNCTION ON THE END)
var myCounter = new Countdown({
seconds: 60, // number of seconds to count down
onUpdateStatus: function(sec){
counterDisplay.html(sec); // display seconds in html
}, // callback for each second
onCounterEnd: function(){
console.log('TIME IS OVER!');
// THIS SHOULD NOT BE HERE, I WOULD PREFER TO MOVE IT SOMEWHERE TO GAME ITSELF
pointsTotalDisplay.html(pointsTotal);
round++; // update to next round
allRounds.hide(); // hide window
mainMenu.show(); // show back again main menu
} // final action
});
var initiateRound = $(".js-initiate");
initiateRound.on("click", function(){ // START GAME
console.log("ROUND " + round + " INITIATED");
points = 0; // reset the points for this round to 0 - not sure this is the way to do it...
console.log(points + " points for this round, " + pointsTotal + " in TOTAL"); // say how many points so far
entryPage.hide();
mainMenu.hide();
allPic.hide();
if( round === 1){
divRound1.show();
pic1.show();
}else if( round === 2){
divRound2.show();
pic2.show();
}else if( round === 3){
divRound3.show();
pic3.show();
}else if( round === 4){
divRound4.show();
pic4.show();
}else if( round === 5){
divRound5.show();
picFinish.show();
initiateRound.hide();
submitNow.hide();
submitResultsFinalBtn.show();
}
counterDisplay.html("60"); //display 60sec on the beginning
myCounter.start(); // and start play time (countdown)
// pointsDisplay.html(points); // display in HTML amount of points for particular round
// if user start collecting points, add them
var mapImage = $('.transparent AREA');
mapImage.each(function(index) {
// When clicked, reveal red circle with missing element
$(this).one("click", function(e) { // YOU CAN CLICK ONLY ONCE!! Using .one() to prevent multiple clicks and eventually scoring more points
e.stopPropagation();
console.log("FIRED");
var theDifference = '#'+$(this).attr('id')+'-diff';
$(theDifference).css('display', 'inline');
if ($(theDifference).data('clicked', true)){ // found circle
// points++;
points += 1;
pointsTotal++;
console.log(points + " points for this round, " + pointsTotal + " in TOTAL");
pointsDisplay.html(points); // display in html amount of points
}
if (points === 6){ // if all points collected (max 6) for this round
myCounter.stop(); // stop countdown
console.log("time stopped, you found all");
setTimeout(function(){ // give him 2sec delay to see last circle marked
allRounds.hide(); // hide window
mainMenu.show(); // show back again main menu
console.log("round " + round + " is finished");
round++; // update to next round
console.log("round " + round + " is activated");
pointsTotalDisplay.html(pointsTotal); // display in HTML total amount of pints
}, 2000);
};
});
});
});
})();
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
Are you sure you're not stacking the $('.transparent AREA') from a round to another ?
This would explain why you score multiple times:
var mapImage = $('.transparent AREA');
mapImage.each(function(index) {
// ...
points++;
// ...
});
Solved!
mapImage.each should be outside of initiateRound

Is there a way to remove all the functions in javascript when timeout?

I have created a drag and drop game. Is there a possible way to stop all the mouseEvents when the time is out?
Below are my codes for the timer.
var canvas = document.getElementById("canvas");
var canvas_context = canvas.getContext("2d");
var text = "you have: 10 : 00 left"
function showFillText() {
canvas_context.clearRect(500, 350, 80, 100);
canvas_context.fillStyle = '#36F'; //text color
canvas_context.font = ' bold 20px sans-serif';
canvas_context.textBaseline = 'bottom';
canvas_context.fillText(text, 500, 450); //('text', x, y)
}
var mins = .1; //Set the number of minutes you need
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
setTimeout('Decrement()',1000);
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
text = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1) setTimeout('Decrement()',1000);
//document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds;
if (currentMinutes == 0 && currentSeconds ==0) {
text = "TIMES UP"
//document.location.href = "http://www.google.com";
}
showFillText()
}
Keep a list of all your event handlers and delete them when your timer expires.
So instead of:
document.getElementById("some element").addEventListener("onX", function () {});
you do:
registerEvent(document.getElementById("some element"), "onX", function () {});
registerEvent keeps a list of all your event listeners. You can remove event listeners with removeEventListener.
It is possible using pointer-events. Use it against a div or class you are interested in. http://caniuse.com/pointer-events
Add a flag called (eg) 'lock', initially set to 0.
When the time is up, set it to 1.
add an if within the function
function myFunction(){
if( lock == 0 ){
... function ...
}
}
There might be a more sophisticated way of doing it but that should work . . .

Categories

Resources