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);
}
}
Related
I would like you to help me for a thing here, for a function to increase and then decrease SVG shape when it hits limit.
It should go from 3 to 6 and then 6 to 3 and so on... but instead it goes from 3 to 6 and then 6 to minus infinite. And I don't understand why.
Here is my code :
var size = 3;
var sizeManager = 1;
function increaseAnimation(el){
var elem = document.getElementById(el);
elem.style.transform = "scale("+size+")";
timer = setTimeout('increaseAnimation(\''+el+'\',3000)');
size=size+0.005*sizeManager;
if(size >= 6){
sizeManager=sizeManager*-1;
}
if (size <= 3){
sizeManager=sizeManager*+1;
}
}
Your weird setTimeout implementation, with bound was broken.
There's also the issue that your sizeManager is not properly reflecting:
function increaseAnimation(id, interval) {
var size = 1;
var velocity = 0.05;
var elem = document.getElementById(id);
function iterate() {
elem.style.transform = "scale(" + size + ")";
size += velocity;
if (size > 2 || size < 1) {
velocity *= -1; // velocity reflected
}
}
var timer = setInterval(iterate, interval);
return function stop() {
clearInterval(timer)
}
}
I also added a stop function which you can call at a later point.
var stopper = increaseAnimation("content", 16);
setTimeout(stopper, 5000);
The error is with the line sizeManager=sizeManager*+1; Multiplying a number by one doesn't change it. You basically want to toggle sizeManager between -1 and +1, and you can do so by multiplying by -1, regardless of whether it is currently negative or positive.
I've tested this code and it seems to work:
var size = 3;
var sizeManager = 1;
function increaseAnimation(el) {
var elem = document.getElementById(el);
elem.style.transform = "scale(" + size + ")";
timer = setTimeout("increaseAnimation('" + el + "', 3000)");
size += 0.005 * sizeManager;
if (size >= 6 || size <= 3) {
sizeManager *= -1;
}
}
Full HTML for a POC demo at: https://pastebin.com/GW0Ncr9A
Holler, if you have questions.
function Scaler(elementId, minScale, maxScale, deltaScale, direction, deltaMsecs) {
var scale = (1 == direction)?minScale:maxScale;
var timer = null;
function incrementScale() {
var s = scale + deltaScale*direction;
if (s < minScale || s > maxScale) direction *= -1;
return scale += deltaScale*direction;
};
function doScale(s) {
document.getElementById(elementId).style.transform = 'scale(' + s + ')';
};
this.getDeltaMsecs = function() {return deltaMsecs;};
this.setTimer = function(t) {timer = t;};
this.run = function() {doScale(incrementScale());};
this.stop = function() {
clearInterval(timer);
this.setTimer(null);
};
};
var scaler = new Scaler('avatar', 3, 6, .05, 1, 50);
function toggleScaler(ref) {
if ('run scaler' == ref.value) {
ref.value = 'stop scaler';
scaler.setTimer(setInterval('scaler.run()', scaler.getDeltaMsecs()));
}
else {
scaler.stop();
ref.value = 'run scaler';
}
};
I am making little reaction game for fun as I am new to this, It's quite a big challenge, so, I ran into the problem, how do I make script to stop from running when the button is pressed, I've managed to start everything when the start is clicked, but can't stop it from running.
Maybe anyone have any ideas how to make this happen? Here's my code so far:
Here's my HTML:
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<p>Your reaction time: <u><span id="timeTaken"></span></u></p>
<p>Your average reaction time: <u><span id="average"></span></u></p>
<p>Your best reaction time: <u><span id="best"></span></u></p>
<div id="shape"></div>
And here's my javascript:
var start = new Date().getTime();
function getRandomColor() { //generates random color
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() { //makes that shape appear on screen
var top = Math.random() * 400;
var left = Math.random() * 400;
var width = (Math.random() * 200) + 100;
if (Math.random() > 0.5) {
document.getElementById("shape").style.borderRadius = "50%"
} else {
document.getElementById("shape").style.borderRadius = "0";
}
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = width + "px";
document.getElementById("shape").style.height = width + "px";
document.getElementById("shape").style.display = "block";
start = new Date().getTime();
}
function appearAfterDelay() { //makes that shape appear after some delay
setTimeout(makeShapeAppear, Math.random() * 3000);
}
document.getElementById("reset").onclick = function() { //reset button, so when you click it, everything resets
location.reload();
}
var totaltime = 0;
var totalgames = 0;
document.getElementById("start").onclick = function() { //start button, so when you click it, shapes start appearing and time's running
appearAfterDelay();
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = "none";
var end = new Date().getTime();
var timeTaken = (end - start) / 1000;
totaltime += timeTaken;
totalgames += 1;
var notroundaverage = (totaltime / totalgames);
var roundaverage = notroundaverage.toFixed(3);
document.getElementById("timeTaken").innerHTML = timeTaken + " s";
document.getElementById("average").innerHTML = roundaverage + " s";
appearAfterDelay();
}
}
JavaScript is event based, and you really shouldn't attempt to 'stop' it. From looking at your code I can see that what you really want to do is clear the timeout when your button is clicked. This can be achieved by placing this line:
var timeOutId;
at the top of your code, and changing
setTimeout(makeShapeAppear, Math.random() * 3000);
to
timeOutId = setTimeout(makeShapeAppear, Math.random() * 3000);
Then, simply add a button with a click event that clears the timeout, which can be achieved using this line: window.clearTimeout(timeOutId);
Hello I am having errors with my code:
https://jsfiddle.net/wzhm2whj/
<script>
//Initial Global variables
var mainloop_frame_time = 34;
var top = 0;
var rootMenu = document.getElementById('menu');
var rootMenuDivs = rootMenu.getElementsByTagName('div')[0];
var rootListDivs = rootMenuDivs.getElementsByTagName('ul')[0];
var childDivs = rootListDivs.getElementsByTagName('div');
var childDiv = childDivs[0];
var childDiv_counter = 0;
var child_change_flag = true;
var child_index_increment = 0;
var child_index_amount = childDivs.length;
//var child_animation_keyframe = 0;
var frame = 0;
var childDiv_tmp1_position = 0;
//finding the web browsers viewport size.
var elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body;
var client_height = elem.clientHeight;
var process_array = new Array();
//Initial styling
for (var i = 0; i < childDivs.length; i++) {
var childDiv = childDivs[0];
childDiv.style.backgroundColor = "antiquewhite";
}
var childDiv = childDivs[0];
//rotate function variables
var rotate_div;
var rotate_passed_deg;
var rotate_deg_stop;
var rotate_results;
var rotate_current_deg = 0;
var speed_modifier = 1;
var tmp1_speed = 0;
//case flags
case2_flag = -1;
case3_flag = -1;
//This may not be needed >>> If not, put all code in mainloop.
var processes_logic = function() {
switch (frame) {
case 0:
process_array.push(menu_child0);
break;
//this case is when the previous case is 80% done
case 28:
rootMenu.style.transformOrigin = "top left";
process_array.push(menu_slant);
break;
case 35:
//Added the ability for paramaters, all push paramaters here are: function, menu_index, position, speed, tmp as flag for switching to next menu,
//process_index used to give the process index as refrence to delete..
window.alert(process_array.length);
process_array.push(new Array(menu_div_slide_out, child_index_amount - 1, 0, 0, 0, process_array.length-1));
break;
}
}
var initiate_all_processes = function() {
for (var i = 0; i < process_array.length; i++) {
//Added the ability for paramaters, considerer removing as its not used atm, or revising.
if (process_array[i] != undefined && process_array[i] != null && process_array[i] != "") {
if (process_array[i].length < 6) {
process_array[i]();
} else {
process_array[i][0](process_array[i][5]);
}
}
}
}
function menu_div_slide_out(process_index) {
/*process_array[process_index][
0 = function,
1 = current menu item (index length working backwards)
2 = position,
3 = speed,
4 = tmp,
5 = refrence to this process in array] */
//for debuging purposes to see if a ChildDiv is not devined, what process index is being pointed to.
//window.alert('Process index ' + process_index);
//!!!!!!!! You are probably mixing up how you are setting process index! try +1
process_array[process_index][2] += 3.5 + (process_array[process_index][3] * 1.7);
process_array[process_index][3] += (speed_modifier * .3);
childDivs[process_array[process_index][1]].style.left = process_array[process_index][2] + 'px';
if (process_array[process_index][2] > 100 && process_array[process_index][4] && process_array[process_index][1] > 0) {
// window.alert('CCC');
process_array[process_index][4] = true;
//Add another process at ever 100pxs
process_array.push(new Array(menu_div_slide_out, process_array[process_index][1] - 1, 0, 0, false, process_array.length-1));
//debugger;
} else
if (process_array[process_index][2] >= (900 - (process_array[process_index][2] / 20))) {
childDivs[process_array[process_index][1]].remove();
//process_array.splice(process_array[process_index][5], 1);
}
}
function menu_slant() {
rotate_return = rotate(rootMenu, .1 + (tmp1_speed), 27);
tmp1_speed += (speed_modifier * .5);
if (rotate_return === true) {
/////////////This can be unremoved because there is more animation, perhaps. or can be done in another key frame.
tmp1_speed = 0;
rotate_current_deg = 0;
remove_process(menu_slant);
} else {
if (rotate_return / 27 * 100 >= 60 && case3_flag < 0) {
case2_flag = frame;
}
}
}
var menu_child0 = function() {
childDiv_tmp1_position += 3 + (tmp1_speed * 1.7);
childDiv.style.top = childDiv_tmp1_position + 'px';
rotate(childDiv, .2 + (tmp1_speed), 170);
tmp1_speed += (speed_modifier * .7);
if (childDiv_tmp1_position / client_height * 100 >= 80 && case2_flag < 0) {
case2_flag = frame;
}
if (childDiv_tmp1_position >= client_height) {
childDiv.style.visibility = 'hidden';
tmp1_speed = 0;
childDiv_tmp1_position = 0;
rotate_current_deg = 0;
//may be bloated >>
remove_process(menu_child0);
}
}
function remove_process(index) {
var index_tmp = process_array.indexOf(index);
if (index_tmp >= 0) {
process_array.splice(index_tmp, 1);
}
}
function rotate(rotate_div, rotate_passed_deg, rotate_passed_deg_stop) {
rotate_current_deg += rotate_passed_deg;
rotate_deg = rotate_current_deg < rotate_passed_deg_stop ? rotate_current_deg : rotate_passed_deg_stop;
rotate_div.style.webkitTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.mozTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.msTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.oTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.transform = 'rotate(' + rotate_deg + 'deg)';
if (rotate_current_deg >= rotate_passed_deg_stop) {
return true;
} else {
return rotate_current_deg;
}
}
//main loop for the animation
var mainloop = function() {
processes_logic();
initiate_all_processes();
frame++;
}
var loop_interval = setInterval(mainloop, mainloop_frame_time);
</script>
I am trying to animate my website falling apart but I am having a hard time articulation this into code. I thought of running the animation in a loop, creating events at specific frames and reusing some codes as functions. I have a rotate function which works to rotate several things.
THE PROBLEM:
The problem I am having is sliding my menu items one at a time to the right. I want one to slide a bit and the next to start sliding after. I wrote a function to slide an item and then in that function it adds another process to an array for the next menu item to be called and run the same function (with passed interval of who is calling). I do not know how many menu items there will be, thats why I am trying to make it dynamic.
I can get it so that the first mwnu item falls, the menu falls by rotating it (some times if there is an error in the code then it wont rotate, but when there are no errors it works better).
The issue is sliding each menu item.
my website is here: http://clearlove.ca/89-404-error
Can any one help me with why this isnt working, and if there is a better way to do what I am trying to do?
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>
I need some javascript help. I am trying to set up two sprite animations with different frame rates in two separate div.
Here is a fiddle I started and i am very much stuck.
How do I combine the two div IDs into one statement? OR Should I be using ClassName in the statement to run on both divs?
http://jsfiddle.net/akwilinski/3t7d6qbL/1/
<div id="animate" class="animation"></div>
<div id="animate2" class="animation2"></div>
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Thank you for any assistance!
Simplest way to do this using the method you have already started using is to define 2 new variables, 1 for the second div and one for the second frame count. Then you can just add the call to your function.
Updated js:
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
var frameOffset2 = (++frame % frames) * -frameHeight - 10;
div.style.backgroundPosition = "0px " + frameOffset + "px";
div2.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Fiddle
http://jsfiddle.net/f4v1vy7x/5/
I made a Can object to store the configuration for each can (so you can have different frameHeights, frames and frameRates.
I used window.requestAnimationFrame because it's far more efficient than setInterval. On each available frame I check whether it's time to animate based on each Can's set frame rate:
var Can = function( selector, frameHeight, frames, frameRate )
{
this.domCan = document.getElementById( selector );
this.frameHeight = frameHeight;
this.frames = frames;
this.frameRate = frameRate;
this.frame = 0;
};
onload = function startAnimation() {
var can1 = new Can( 'animate', 400, 27, 20 );
var can2 = new Can( 'animate2', 400, 27, 100 );
var cans = [ can1, can2 ];
window.requestAnimationFrame( function() {
can1.start = can2.start = new Date();
animate( cans );
} );
};
var animate = function( cans ) {
for( var i = 0; i < cans.length; i++ ) {
var now = new Date();
var can = cans[i];
if( now - can.start >= 1000 / can.frameRate ) {
can.start = now;
var frameOffset = (++can.frame % can.frames) * -can.frameHeight;
can.domCan.style.backgroundPosition = "0px " + frameOffset + "px";
}
}
window.requestAnimationFrame( function() {
animate( cans );
} );
}
You could do something like this:
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
function anim(div) {
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
anim(div);
anim(div2);
You could then pass in additional parameters like frameHeight, frame, and frames to further customize each animation.