Continually fade background box with each click of the fade button - javascript

Brand new to coding. Trying to get "fade" button to fade a little more each time I click it.
I have used this code to grow and shrink the box and I was trying to do the same thing for the opacity:
document.getElementById("growbutton").addEventListener("click", function() {
var growVariable = 10;
var newValueHeight = parseInt(document.getElementById("box").style.height)
document.getElementById("box").style.height = newValueHeight + growVariable + "px";
var newValueWidth = parseInt(document.getElementById("box").style.width)
document.getElementById("box").style.width = newValueWidth + growVariable + "px";
});
document.getElementById("fadebutton").addEventListener("click", function() {
var opVariable = .2;
var newOpValue = parseInt(document.getElementById("box").style.opacity)
document.getElementById("box").style.opacity = newValueHeight - opVariable;
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>
Can you tell me what I'm missing so the box fades .2 with each click?

Your existing code produces the error: Uncaught ReferenceError: newValueHeight is not defined. There were a few issues:
You were referencing newValueHeight instead of newOpValue by accident.
parseInt() will return an integer, i.e., if the current opacity is 0.8, parseInt(0.8) returns 1. You need to use parseFloat() to get a floating point back.
Initially, style.opacity is undefined because it has not been set yet. You should use opValue = ... || 1 so that it defaults to 1 if not yet set.
let box = document.getElementById('box'),
fadeBtn = document.getElementById('fadebutton'),
growBtn = document.getElementById('growbutton');
growBtn.addEventListener('click', function() {
let growVariable = 10,
boxHeight = parseInt(box.style.height),
boxWidth = parseInt(box.style.width);
box.style.height = boxHeight + growVariable + "px",
box.style.width = boxWidth + growVariable + "px";
});
fadeBtn.addEventListener("click", function() {
let opVariable = .2,
opValue = parseFloat(box.style.opacity) || 1;
box.style.opacity = opValue - opVariable;
});
<div id="box" style="height: 100px; max-height: 600px; min-height: 5px; width:100px; max-width: 600px; min-width: 5px; background-color:orange; margin:1rem"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>

You need to use parseFloat when dealing with non-whole numbers or with decimal points as parseInt returns an integer or a whole number
document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>

document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>

If you just want to fade the image onclick, you can simply decrement the style.opacity property. Something like this:
const box = document.querySelector('#box');
document.addEventListener('click', e => {
if (e.target.id === 'fadebutton') {
if (box.style.opacity > 0) {
box.style.opacity -= .2;
}
}
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px; opacity: 1"></div>
<button id="fadebutton">Fade</button>

Related

How to make button randomly change position when clicked

When I click on the button, I would like the position of the button to change to a random location.
Here is what I have tried:
var b = document.querySelector("button");
b.addEventListener("click",change);
var i = Math.floor(Math.random()*500)+1;
var j = Math.floor(Math.random()*500)+1;
function change()
{
b.style.left = i+"px";
b.style.top = j+"px";
}
button{
margin-left: auto;
margin-right: auto;
display: block;
position: absoulte;
}
<button>
Hello World
</button>
Define i and j inside change() method so that it can be randomly updated when button is clicked.
Also, there is a typo in your code position: absoulte which should be corrected to absolute
var b = document.querySelector("button");
b.addEventListener("click",change);
function change()
{
var i = Math.floor(Math.random()*500)+1;
var j = Math.floor(Math.random()*500)+1;
b.style.left = i+"px";
b.style.top = j+"px";
}
button{
display: block;
position: absolute;
}
<button>abc</button>
HTML :-
<body>
<div class="ctr">
<button class="button" id="movingbutton">Button</button>
</div>
</body>
CSS:-
#movingbutton{
margin-left: auto;
margin-right: auto;
display: block;
position: absolute;
left : 20px;
top : 50px;
}
body{
width : 100%;
}
.ctr{
width : 100%;
height : 100%;
}
JS:-
var b = document.querySelector("#movingbutton");
b.addEventListener("click",change);
function change()
{
let i =Math.abs(Math.floor(Math.random()*window.innerWidth-55))
let j = Math.abs(Math.floor(Math.random()*window.innerHeight-21));
console.log('here' , i ,j , b.style.left , b.style.top);
b.style.left = i+'px';
b.style.top = j + "px";
}
If you want you can check here: Live example link
You need to add one more condition if that button goes outside window.innerWidth and window.innerHeight
You'll need to move the random calculation inside the change() function.
To keep the element within it's containing element you can use getBoundingClientRect(). (And account for the size of the button to avoid overlaps on the right and bottom using the same.)
const c = document.querySelector(".container");
const b = document.querySelector("button");
function change() {
const
{ width: cWidth, height: cHeight } = c.getBoundingClientRect(),
{ width: bWidth, height: bHeight } = b.getBoundingClientRect(),
i = Math.floor(Math.random() * (cWidth - bWidth)) + 1,
j = Math.floor(Math.random() * (cHeight - bHeight)) + 1;
b.style.left = i + "px";
b.style.top = j + "px";
}
b.addEventListener("click", change);
.container {
position: relative;
height: 50vh;
width: 50vw;
background-color: lightgray;
}
button{
position: absolute;
display: block;
}
<div class='container'>
<button type='button' id='shifty'>Click</button>
</div>
If you want to move randomly a button you can use simple .bind(). You can also move button when your mouse is moving in button area(without clicking it) .
Here are both codes:
Code for click
var b = document.querySelector("#movingbutton");
b.addEventListener("click",change);
function change()
{
let i = Math.floor(Math.random()*500)+1;
let j = Math.floor(Math.random()*500)+1;
console.log('here' , i ,j , b.style.left , b.style.top);
b.style.left = i+'px';
b.style.top = j + "px";
}
#movingbutton{
margin-left: auto;
margin-right: auto;
display: block;
position: absolute;
left : 20px;
top : 50px;
}
body{
width : 100%;
}
.ctr{
width : 100%;
height : 100%;
}
<body>
<div class="ctr">
<button class="button" id="movingbutton">Button</button>
</div>
</body>
Code for mousemove
var b = document.querySelector("#movingbutton");
b.addEventListener("mousemove",change);
function change()
{
let i = Math.floor(Math.random()*500)+1;
let j = Math.floor(Math.random()*500)+1;
console.log('here' , i ,j , b.style.left , b.style.top);
b.style.left = i+'px';
b.style.top = j + "px";
}
#movingbutton{
margin-left: auto;
margin-right: auto;
display: block;
position: absolute;
left : 20px;
top : 50px;
}
body{
width : 100%;
}
.ctr{
width : 100%;
height : 100%;
}
<body>
<div class="ctr">
<button class="button" id="movingbutton">Button</button>
</div>
</body>

how to make a box reach the edge of a bigger box

javascript beginner here! so i'm trying to do a box(that is inside a larger box) move from the top to the edge of the box. Here's the code:
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 320) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>
The problem is that the small box doesn't exactly ends up at the edge, it goes more to the right. I tried doing
boxcont.style.left = (loc - 0.5) + "px";
but doesn't work. pretty sure the solution is simple but as a newbie here it's confusing me :p. Oh and i also tried doing ++ to the 0.5 and Number(0.5) so it reads it as a decimal but still doesn't work!
the big gray box is not set to the correct height and width that corresponds with the small red box's movement. You have it going down 1 and to the right 1 every 5 however, your actually going across a rectangle, not a square. set your width and height the same for the gray box and slightly adjust the stopping point to a little bit less.
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5); // every five milliseconds
function boxmove() {
if (loc == 290) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox" style = "height: 320px; width: 320px">
<div id="boxcont" ></div>
</div>
<button id="boxbtn">Move the box</button>
if (loc == 270) {
instead of
if (loc == 320) {
Gets you there.
300px is the width of the containing div and the moving div is 30px wide so 300-30=270px
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 270) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>

set new element class property value

How to add 10px to an css class property with javascript?
for example:
var bigger = document.getElementsByClassName("size200").style.width;
bigger + 10;
To achieve expected result ,use below option
let width = document.getElementsByClassName("size200")[0].clientWidth + 10;
document.getElementsByClassName("size200")[0].style.width = width + 'px'
codepen - https://codepen.io/nagasai/pen/roazyL
let width = document.getElementsByClassName("size200")[0].clientWidth + 10;
document.getElementsByClassName("size200")[0].style.width = width + 'px'
.size200{
width: 200px;
border: 1px solid black;
height: 20px
}
.size100{
width: 200px;
border: 1px solid black;
height: 20px
}
<div class="size200">
</div>
<div class="size200">
</div>
<div class="size100">
</div>
Above solution will change only first class , to apply for every element with same class
for(var i = 0; i < document.getElementsByClassName("size200").length; i++){
let width = document.getElementsByClassName("size200")[i].clientWidth + 10;
document.getElementsByClassName("size200")[i].style.width = width + 'px'
}
codepen - https://codepen.io/nagasai/pen/vvEJRz
setTimeout(() => {
// get width
let width = window.getComputedStyle(document.querySelector('.some-class')).width;
width = +width.substr(0,width.length-2);
let newWidth = `${width+100}px`;
// set style
Array(document.getElementsByClassName('some-class').length)
.fill()
.map((_, index) => {
document.getElementsByClassName('some-class')[index].style.width = newWidth;
});
}, 1000)
.some-class {
width: 200px;
height: 200px;
background-color: red;
transition: all .5s;
}
<div class="some-class"></div>
<p>
wait 1s
</p>
<div class="some-class"></div>

Why is animation (transition) not applied the first time the property is set

Here is a simple setup with a box moving using left property to the right. The property is updated by a button click. Why is transition animation not applied the first time I click on the button?
document.addEventListener('DOMContentLoaded', () => {
const box = document.querySelector('.box');
const button = document.querySelector('button');
button.addEventListener('click', () => {
const current = parseInt(box.style.left);
box.style.left = (isNaN(current) ? 0 : current) + 50 + "px";
});
})
.box {
width: 100px;
height: 100px;
background: green;
position: relative;
transition: left 1s;
}
<button>Click me!</button>
<div class="box"></div>
The initial value of left is auto and auto is not a transitionable value.
You would need to explicitly set left: 0 to have a transition then.
Start with some initial value for left.
document.addEventListener('DOMContentLoaded', () => {
const box = document.querySelector('.box');
const button = document.querySelector('button');
button.addEventListener('click', () => {
const current = parseInt(box.style.left);
box.style.left = (isNaN(current) ? 0 : current) + 50 + "px";
});
})
.box {
left: 0;
width: 100px;
height: 100px;
background: green;
position: relative;
transition: left 1s;
}
<button>Click me!</button>
<div class="box"></div>
As "left" property is intialized as "auto", no transitions can be applied.
Instead try this:
document.addEventListener('DOMContentLoaded', () => {
const box = document.querySelector('.box');
const button = document.querySelector('button');
button.addEventListener('click', () => {
const current = parseInt(box.style.left);
box.style.left = (isNaN(current) ? 0 : current) + 50 + "px";
});
})
.box {
left: 0;
width: 100px;
height: 100px;
background: green;
position: relative;
transition: left 1s;
}
<button>Click me!</button>
<div class="box"></div>

Why is putting style inside if statement not working?

I'm trying to do a basic toggle clicking with js... I have this
<div id="box"></div>
<button id="btn"></button>
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
js:
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (box.style.left === '50px') {
box.style.left = '200px';
}
if (box.style.left === '200px') {
box.style.left = '50px';
}
});
I looked it up and this seems to be the method everyone uses for toggle clicking with pure js so I have no idea why it's not working for me, any ideas?
You should use the window.getComputedStyle instead (This way you will get the actual value of the style that applied to that element, and not just what's on the style attribute)..
You are missing an else there (otherwise you will always get the two if and nothing will change)
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (window.getComputedStyle(box).left === '50px') {
box.style.left = '200px';
} else if (window.getComputedStyle(box).left === '200px') {
box.style.left = '50px';
}
});
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
<div id="box"></div>
<button id="btn"></button>
#Dekel's answer already explains what was wrong with your code. However, you should work with classes instead. Not only is this way faster than retrieving window.getComputedStyle, it's also much easier
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var box = document.getElementById('box');
box.classList.toggle('left-50');
box.classList.toggle('left-200');
});
.left-50 {
left: 50px;
}
.left-200 {
left: 200px;
}
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
}
<div id="box" class="left-50"></div>
<button id="btn">bt</button>
Better use offset. Beside you are making a kind of toggle operation in here. Meanwhile, I modified your script to make it work:
<div id="box"></div>
<input type="button" id="btn" value=" Try it ">
<style>
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
</style>
<script>
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (box.offsetLeft == 50 ) {
box.style.left = 200 ;
}
else if (box.offsetLeft == 200 ) {
box.style.left = 50;
}
});
</script>

Categories

Resources