Div opacity not working - javascript

I have a timer on my div which changes the opacity of the div. But for some reason the maths keeps setting it to 0.1 over and over. And i have no idea why!
This is my code:
function do_it(div){
var opac = parseInt(div.style.opacity);
if(opac == 1){
var dir = 'down';
} else if(opac == 0) {
var dir = 'up';
}
if(dir == 'down'){
opac -= 0.1;
} else {
opac += 0.1;
}
if(opac > 1){
opac = 1;
} else if(opac < 0){
opac = 0;
}
div.style.opacity = opac;
div.timer = setTimeout(function(){ do_it(div) }, 1000);
}
Have provided a fiddle:
JSFiddle
The div opacity should go from 1 to 0 and back up again in steps of 0.1

This is your problem
var opac = parseInt(div.style.opacity);
It should be parseFloat
var opac = parseFloat(div.style.opacity);

function do_it(div,output){
var opac = parseFloat(div.style.opacity);
opac -= 0.1;
if(opac<=0.05){
opac = 1;
}
div.style.opacity = opac;
output.innerHTML = opac;
div.timer = setTimeout(function(){ do_it(div,output) }, 1000);
}
var div = document.getElementById('test');
var output = document.getElementById('op');
do_it(div,output);
parse a number
parseInt(0.9) ==> 0
parseFloat(0.9) ==>0.9
there is no need of extra vars lik up down
http://jsfiddle.net/ckBFy/29/

Even though there's already an accepted answer, I'd like to add that I think that it's still not working the way it was supposed to.
Here's a link to my demo (the way I believe it should have worked).
And here's my corrected version of the code:
way = 'down';
function do_it(div,output){
var opac = parseFloat(div.style.opacity);
if(opac >= 1){
way = 'down';
}
else if(opac <= 0.2) {
way = 'up';
}
if (way === 'down'){
opac -= 0.1;
}
else{
opac += 0.1;
}
div.style.opacity = opac;
output.innerHTML = opac;
div.timer = setTimeout(function(){ do_it(div,output) }, 1000);
}
var div = document.getElementById('test');
var output = document.getElementById('op');
do_it(div,output);

Related

How to activate an interval when a certain position is reached?

The problem is that It calls the var intervalLeft and intervaRight at the same time. When it is moving right I want the intervalLeft not to work & vice versa.
When It reaches startPosition 100 it activates the intervalLeft and when it reaches startPosition 0 it activates intervalRight infinite.
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var intervalLeft = setInterval(frameLeft, 10);
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalRight);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.right = startPosition + "%";
}
}
}
</script>
This is the exercise:
Below this, you have a div that needs to move left to right using JS for the motion. Make it reach the end in 2 seconds, then return in 5s. Repeat that forever.
Have updated your code. Use below
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var rightTimer = true;
var leftTimer = false;
var intervalLeft;
function frameRight() {
if(!rightTimer){
rightTimer = true;
intervalRight = setInterval(frameRight,10)
return;
}
if (startPosition >= 100) {
rightTimer = false;
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if(!leftTimer){
leftTimer = true;
intervalLeft = setInterval(frameLeft,10)
return;
}
if (startPosition <= 0) {
leftTimer = false;
clearInterval(intervalLeft);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>
After testing some more i've found the answer with fewer lines of code.
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10); //1
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
intervalLeft = setInterval(frameLeft, 10);
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalLeft);
intervalRight = setInterval(frameRight, 10);
} else {
startPosition -= 0.2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>
this works how it Should. In the original code I posted the clearInterval was not linked to an actual intervalID

how to run JavaScript game animations sequentially after each one is finished

Currently, I am using an archaic method of setting a variable true at the start of the animation and false after the animation has played (see below.) I also think something might be wrong with how I process animations in the interval because when I add an animation to the array of animations to be processed, it isn't processed. Here's my code:
var animationDone = true;
function g_e(e){
return document.getElementById(e);
};
class Main{
constructor(){
this.animations = [];
this.tasks = [];
}
start_animating(){
var x = setInterval(function (){
if (animationDone == true){
try{
alert(this.animations[0]);
this.aminations[0].func(this.animations[0].args);
this.animations.shift();
}
catch(e){
}
}
},1);
}
add_animation(f, a){
this.animations.push({func:f, args:a});
alert("animation added");
}
start_working(){
var x = setInterval(function (){
try{
this.tasks[0].func(this.tasks[0].args);
this.tasks.shift();
}
catch(e){
}
},1);
}
animation_blink(){
var blink = 0;
window.setInterval(function blinking(){
if (blink == 0){
document.getElementById("blinker").innerHTML = ">";
blink= 1;
}
else if(blink == 1){
document.getElementById("blinker").innerHTML=" ";
blink = 0;
}
}, 1000);
}
animation_fade(object){
var fade = 0;
var fadeOut = 0;
animationDone = false;
var interval = setInterval(function startFade(){
g_e(object.element).style.opacity = fade;
if(fade>1 && fadeOut == 0){
fadeOut = 1;
}
else if(fade < 0){
clearInterval(interval);
}
else if(fadeOut == 0){
fade = fade + 0.2;
}
else if(fadeOut == 1){
fade = fade - 0.2;
}
}, 500);
animationDone = true;
}
plbl(object){
animationDone = false;
var p = plbl.intervals;
if (!p)
plbl.intervals = p = {};
if (p[object.destination])
clear();
function clear() {
clearInterval(p[object.destination]);
delete p[object.destination];
}
var i = 0;
var elem = document.getElementById(object.destination);
p[object.destination] = setInterval(function(){
checkChar = object.message.charAt(i);
if(checkChar =="|"){
elem.innerHTML += "<br>";
}
else{
elem.innerHTML += object.message.charAt(i);
}
i++;
if (i > message.length){
animationDone = true;
clear();
}
}, object.speed);
}
command(input){
alert(input);
if(input == "y"){
g_e("start").style.display = "none";
g_e("startUp").style.display = "block";
this.add_animation("test", "test");
}
}
get_input(){
var x = g_e("input").value;
g_e("input").value = "";
return x;
}
key_checker(event){
var key = event.keyCode;
if (key == 13){
this.command(this.get_input());
return false;
}
}
start(){
this.start_working();
this.start_animating();
this.animation_blink();
}
}
alert("compiled");
main = new Main();
main.start();

Link the movement of a div to the movement of another div

I'm making an alcohol simulator, so when I press a button, you see an alcohol bottle being drained, but at the same time I should see the stomach filling. I have a code already for 'drinking', but I want to fix that if the water of the bottle moves 2 steps, that the water of the stomach only moves one step. I'll put just the js here, if you want the html as well, let me know.
var top_max = 475,
top_min = 400,
left_max = 200;
function move_img(str) {
var step = 1; // change this to different step value
var el = document.getElementById('i1');
var el2 = document.getElementById('i2');
if (str == 'up' || str == 'down') {
var top = el.offsetTop;
var height = el.offsetHeight;
console.log(height);
if (str == 'up') {
top -= step;
height += step;
} else {
top += step;
height -=step;
}
if (top_max >= top && top >= 110) {
document.getElementById('i1').style.top = top + "px";
document.getElementById('i1').style.height = height;
} else {
clearInterval(myVar)
}
} else if (str == 'left' || str == 'right') {
var left = el.offsetLeft;
if (str == 'left') {
left += step;
} else {
left -= step;
}
if (top_left < left && left >= 0) {
document.getElementById('i1').style.left = top + "px";
} else {
clearInterval(myVar)
}
}
}
function auto(str) {
myVar = setInterval(function () {
move_img(str);
}, 90);
}
function nana() {}
var myVar;
function handler() {
clearInterval(myVar);
auto(this.id);
}
function auto(str) {
myVar = setInterval(function(){ move_img(str); }, 2) ;
}
function stop(){
setTimeout(function( ) { clearInterval( myVar ); }, 1);
}

addEventListener onClick not working

I don't know what's wrong with my code, but when I use addEventListener() it doesn't do a thing.
Does anyone have another solution so that I can bind the #ibm button ID to compute() onClick event?
I plan to run this on Firfox OS, so setting an onClick attribute on the button itself is prohibited as stated on the CSP Violations.
function compute()
{
var w = parseInt(document.getElementById('weight').value);
var hf = parseInt(document.getElementById('height_ft').value);
var hi = parseInt(document.getElementById('height_in').value);
if (!checker(w))
{
showAndroidToast('Please input your weight');
return;
}
else if (!checker(hf))
{
showAndroidToast('Please input your height');
return;
}
if (!checker(hi))
{
var i = 0;
document.getElementById('height_in').value = i;
}
else
{
var i = parseInt(document.getElementById('height_in').value);
}
var comp_h = parseFloat((hf * 12) + (i * 1));
var tot_h = comp_h * comp_h;
comp = formula(w, tot_h);
document.getElementById('bmitot').value = comp;
if (comp > 30)
{
document.getElementById('res').value = 'Severe Level! Thats too much FAT! Go get some diet pills or something!';
document.getElementById("bmitot").style.backgroundColor = "red";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "visible";
}
if (comp > 25 && comp <=29.9)
{
document.getElementById('res').value = 'Bad Level! You are too FAT!';
document.getElementById("bmitot").style.backgroundColor = "yellow";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "visible";
document.getElementById("three").style.visibility = "hidden";
}
if (comp > 18.5 && comp <=24.9)
{
document.getElementById('res').value = 'Nice! You are on the safe level!';
document.getElementById("bmitot").style.backgroundColor = "green";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "visible";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "hidden";
}
if (comp < 18.5)
{
document.getElementById('res').value = 'Bad Level! Go get some nutrients!';
document.getElementById("bmitot").style.backgroundColor = "yellow";
document.getElementById("zero").style.visibility = "visible";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "hidden";
}
}
function formula(w, h)
{
var bmi = w/h * 703;
var a_bmi = Math.floor(bmi);
var dif = bmi - a_bmi;
dif = dif * 10;
diff = Math.round(dif);
if (dif == 10)
{
a_bmi += 1;
dif = 0;
}
bmi = a_bmi + "." + diff;
return bmi;
}
function checker(type)
{
if (isNaN(parseInt(type)))
{
return false;
}
else if (type < 0)
{
return false;
}
else
{
return true;
}
}
function showAndroidToast(toast)
{
Android.showToast(toast);
}
document.getElementById('ibm').addEventListener('click', compute);
Your code is executing fine and compute function is triggering fine. There may be an issue with the code in execute function. Check this fiddle

setInterval animation

http://jsfiddle.net/vzBZB/5/
(function(){
var i = 1;
var start = true;
setInterval(function(){
if (i>0&&start){
var o = $("#box").css("opacity");
var s = parseFloat(o) - 0.1;
$("#box").css("opacity", s.toString());
i = s;
}
else {
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if (i==1) start = true;
}
}, 100);
})();
This code does simple animation - it goes from opacity 1 to 0 and back to 1. But i would like to perform this cycle infinitely. i used if (i==1) start = true; but it doesnt help. how do i fix? Second question: when it stops opacity is 1.1. Why? How do i fix?
How about just set "start" back to true when you're done fading back in. Such as:
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if(s >= 1) start = true; //Reset for next loop
Here's my working example: http://jsfiddle.net/vzBZB/8/
You may find it easier to simply use the callback parameter of .fadeToggle recursively. See my update to your jsfiddle: http://jsfiddle.net/vzBZB/6/.
You arent setting start back to true when it gets back to full opacity...
add this
if (o >= 1){
start=true;
}
full code:
(function(){
var i = 1;
var start = true;
setInterval(function(){
if (i>0&&start){
var o = $("#box").css("opacity");
var s = parseFloat(o) - 0.1;
$("#box").css("opacity", s.toString());
i = s;
}
else {
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if (o >= 1){
start=true;
}
}
}, 100);
})();

Categories