I'm creating a website and i'm trying to make a button that will toggle the visibility of a div element. it works for me right now but I want to add an animation to it and I just can't pull it off.
I tried changing the "block"
to fadeIn()
and the "none"
to fadeOut()
but that didn't work.
Any ideas?
function pcsh1() {
var x = document.getElementById("pc1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="pcsh1()">Show / Hide PC 1</button>
<div id="pc1">
<textarea rows="2" cols="20" placeholder="PC Name" class="pcbox">PC Name: </textarea>
<textarea rows="2" cols="20" placeholder="Alignment" class="pcbox">Alignment: </textarea>
<textarea rows="2" cols="20" placeholder="Max HP" class="pcbox">Max HP: </textarea>
<textarea rows="2" cols="20" placeholder="Current HP" class="pcbox">Current HP: </textarea>
</div>
The output currently is great but I would prefer it to have an animation.
You could use the CSS transition
rule and simply toggle a CSS class on the target element using JavaScript. transition
will let you change one, or several CSS rules on an element.
transition
Transitions enable you to define the transition between two states of an element...
Here is an example
var btn = document.getElementsByTagName('button')[0]
var p = document.getElementsByTagName('p')[0]
btn.addEventListener('click', evt => {
p.classList.toggle('show')
})
.show {
opacity: 1;
}
p {
opacity: 0;
transition: opacity 0.6s linear;
}
<button>Click Me</button>
<p>Hello</p>
With your example this is how you could do it:
var btn = document.getElementsByTagName('button')[0];
var pc1 = document.getElementById('pc1');
btn.addEventListener('click', function() {
pc1.classList.toggle('hide');
});
#pc1 {
opacity: 1;
transition: opacity 0.5s linear;
}
#pc1.hide {
opacity: 0;
}
<button>Show / Hide PC 1</button>
<div id="pc1">
<textarea rows="2" cols="20" placeholder="PC Name" class="pcbox">PC Name: </textarea>
<textarea rows="2" cols="20" placeholder="Alignment" class="pcbox">Alignment: </textarea>
<textarea rows="2" cols="20" placeholder="Max HP" class="pcbox">Max HP: </textarea>
<textarea rows="2" cols="20" placeholder="Current HP" class="pcbox">Current HP: </textarea>
</div>
I would suggest toggling hide/show using the animation-friendly opacity prop instead of display in the following manner:
function pcsh1() {
var x = document.getElementById("pc1");
if (x.classList.contains("hide")) {
x.classList.remove("hide");
} else {
x.classList.add("hide");
}
}
and adding a css transition:
#pc1 {
opacity: 1;
transition: opacity 1s;
}
#pc1.hide {
opacity: 0;
}
here is an example codepen: https://codepen.io/mikeCky/pen/WWjLEq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With