Doesn't work after writing it inside a class - javascript

I'm practicing some Javascript and I'm trying to figure out how to move a div from the left of the screen to the right. I did this in a separate file to test it first and it works, however, if I create a class and put my functions and variables inside it stops working and Firebug doesnt give me back any error. Can anyone help me?
Here's the code I figured out:
function crear_div (){
this.pos_x = 10;
this.pos_y = 10;
this.x_min = 10;
this.x_max = 500;
this.y_min = 10;
this.y_max = 500;
this.incremento = 10;
this.estado = 0;
this.id_elemento = "pelota";
this.f0 = f0;
this.f2 = f2;
}
function f0(){
this.pos_x = this.pos_x + this.incremento;
document.getElementById(this.id_elemento).style.left = this.pos_x + "px";
if (this.pos_x >= this.x_max){
this.estado = 1;
}
}
function f2(){
this.pos_x = this.pos_x - this.incremento;
document.getElementById(id_elemento).style.left = this.pos_x + "px";
if (this.pos_x <= this.x_min){
this.estado = 0;
}
}
function desplazar(){
switch(this.estado){
case 0:
this.f0();
break;
case 1:
this.f2();
break;
}
}
window.setInterval(function () {this.desplazar();}, 250);

You need to create an object of the class, and use it in the interval function:
var the_div = new crear_div();
window.setInterval(function() {
the_div.desplazar();
}, 250);

Related

I have some JavaScript function that keeps repeating itself, I can't find why

This is code that generates a selected image when a function is run, but the image keeps changing, I want this code to let me have one image and keep it that way instead of it changing randomly every 0.5 - 3 seconds, and I don't know why!
const imageSelector = document.querySelector("#changeHeron")
function spinMachine() {
document.getElementById('spinner').disabled = 'disabled';
spinner.style.transform = "rotate(90deg)";
setInterval(enterBall, 1000)
var protmt = prompt("What's your name?")
alert("Hey there " + protmt + ", " + "its great to see you here")
}
function enterBall() {
var ball = document.getElementById("changeHeron");
ball.style.opacity = "100%";
ball.style.transform = "ScaleX(50%) ScaleY(50%)";
setInterval(liftBall, 1000);
}
function liftBall() {
var ball = document.getElementById("changeHeron");
ball.style.transform = "translateY(-250%)";
ball.style.transform = "ScaleX(200%) ScaleY(200%)";
ball.style.top = "40%";
setInterval(changeImage, 1500);
}
function changeImage() {
var images = ["./Images/Football.png", "./Images/Mousetache.png", "./Images/OG.svg"];
var randomNum = Math.floor(Math.random() * images.length);
var ball = document.getElementById("changeHeron");
ball.src = images[randomNum];
ball.style.borderRadius = "5%";
ball.style.backgroundColor = "white";
}
I found that you can place the images varible outside and change it inside when the code has ran so that the rest can just work outside of this problem

Can`t move element on setInterval function

I have a small image that may change his background-position-x on hover event. And stop moving on mouseleave. But even with setInterval my fuctuin run just 1 time. Here`s my code. Could someone help me?
let wave = document.querySelector('.wave');
wave.onmouseover = moveWave();
function moveWave() {
setInterval(function () {
wave.style.backgroundPositionX += 10 + 'px';
}, 100)
}
The problem is with below line:
wave.style.backgroundPositionX += 10 + 'px';
After first call, the wave.style.backgroundPositionX will be:
10px
After next call, the wave.style.backgroundPositionX will be:
10px10px -> which is incorrect format.
The right way is:
var count = 10;
let wave = document.querySelector('.wave');
wave.onmouseover = moveWave();
function moveWave() {
setInterval(function () {
count += 10;
wave.style.backgroundPositionX = count + 'px';
}, 100)
}
var count = 10;
let wave = document.querySelector('.wave');
wave.onmouseover = moveWave();
wave.onmouseleave = moveLeave();
var id;
function moveWave() {
id = setInterval(function () {
count += 10;
wave.style.backgroundPositionX = count + 'px';
}, 100)
}
function moveLeave() {
clearInterval(id);
}

How can I make my outputs cycle up or down to the final answer?

I've got a simple simulator code where the user selects buttons to vary the inputs, and the outputs change in response (an example extract of which is shown below).
However, the outputs update automatically to the solution, and I was wondering if there's a way to show the numbers ticking over and increasing from what was previously displayed to the new number?
html
<button onClick = "IncTHR()">Increase Throttle</button>
<button onClick = "DecTHR()">Decrease Throttle</button>
<input type="text" id="THR">
<div id="CoolantTemp1"></p>
javascript
var CoolantTemp1 = 366;
var Throttle = 5;
var ControlRodHeight = 50;
var PrimaryPump = 1;
function IncTHR(){
user = ++Throttle;
if (Throttle > 10){
Throttle = 10;
}
CoolantTemp1 = (220+(ControlRodHeight*2.2)+(PrimaryPump*20)+(Throttle*3.2));
update();
displayResults();
function DecTHR(){
user = --Throttle;
if (Throttle < 0){
Throttle = 0;
}
CoolantTemp1 = (220+(ControlRodHeight*2.2)+(PrimaryPump*20)+(Throttle*3.2));
update();
displayResults();
function update() {
document.getElementById("THR").value = Throttle;
}
function displayResults() {
document.getElementById("CoolantTemp1").innerHTML = "Coolant Temperature 1 is " + CoolantTemp1;
}
So currently, as soon as the user clicks either throttle button, the Coolant Temperature is updated immediately to the solution - is there a way for the output to cycle through from the number it previously was to the new number it will become as a result of the calculation change?
Hope that makes sense!
Thank you.
Something like this should work:
var CoolantTemp1 = 366;
var tempCounter = 366;
var Throttle = 5;
var ControlRodHeight = 50;
var PrimaryPump = 1;
function IncTHR(){
Throttle++;
if (Throttle > 10){
Throttle = 10;
}
CoolantTemp1 = (220+(ControlRodHeight*2.2)+(PrimaryPump*20)+(Throttle*3.2));
update();
var incInt = setInterval(function (){
if (tempCounter < CoolantTemp1){
displayResults(tempCounter);
tempCounter++;
} else {
displayResults(CoolantTemp1);
tempCounter = CoolantTemp1;
clearInterval(incInt);
}
}, 1000);
}
function DecTHR(){
Throttle--;
if (Throttle < 0){
Throttle = 0;
}
CoolantTemp1 = (220+(ControlRodHeight*2.2)+(PrimaryPump*20)+(Throttle*3.2));
update();
var decInt = setInterval(function (){
if (tempCounter > CoolantTemp1){
displayResults(tempCounter);
tempCounter--;
} else {
displayResults(CoolantTemp1);
tempCounter = CoolantTemp1;
clearInterval(decInt);
}
}, 1000);
}
function update() {
document.getElementById("THR").value = Throttle;
}
function displayResults(temp) {
document.getElementById("CoolantTemp1").innerHTML = "Coolant Temperature 1 is " + temp;
}

program flow animating in javascript

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?

Check if all percentages in the array were shown

I'm using this Code to show the current progress in my progressbar:
var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;
function initRotateText() {
rotatingTextElement = document.getElementById("percent");
rotatingText[0] = rotatingTextElement.innerHTML;
rotatingText[1] = "5%";
rotatingText[2] = "10%";
rotatingText[3] = "15%";
rotatingText[4] = "20%";
rotatingText[5] = "25%";
rotatingText[6] = "30%";
rotatingText[7] = "35%";
rotatingText[8] = "40%";
rotatingText[9] = "45%";
rotatingText[10] = "50%";
rotatingText[11] = "55%";
rotatingText[12] = "60%";
rotatingText[13] = "65%";
rotatingText[14] = "70%";
rotatingText[15] = "75%";
rotatingText[16] = "80%";
rotatingText[17] = "85%";
rotatingText[18] = "90%";
rotatingText[19] = "95%";
rotatingText[20] = "100%";
setInterval(rotateText, 500);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;
It basicly writs a new percentage in span#percent every 500 miliseconds.
The problem is that after the progressbar has reached 100% it starts again with 0%, 5% and so on.
How can I check if the percentages in the array rotatingText till [20] were all shown and then stop the rotation?
Do this instead:
var rotatingTextElement = document.getElementById("percent");
var ctr = 0;
function rotateText() {
rotatingTextElement.innerHTML = ctr + "%";
ctr += 5;
if (ctr <= 100) {
window.setTimeout(rotateText, 500);
}
}
rotateText();
There are a few ways you can tidy this up. To answer your question, start by assigning the interval to a variable:
var rotator = null;
...
rotator = setInterval(rotateText, 500);
...
function rotateText() {
ctr++;
if(ctr >= rotatingText.length -1) {
clearInterval(rotator);
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
...
Then instead of resetting the iterator to 0 when it goes out of bounds, clear the interval so it stops changing the value. You'll need to add the -1 so that it stops on rotatingText[length-1] (the last element)

Categories

Resources