When I am hovering over a DIV, it increases in both height and width but I have no idea how to make it animate smoother instead of resize all at once
function chg()
{
document.getElementById("d1").innerHTML="Great Job!";
document.getElementById("d1").style.width="300px";
document.getElementById("d1").style.height="200px";
}
function chg2()
{
document.getElementById("d1").innerHTML="Hover Over Me!";
document.getElementById("d1").style.width="230px";
document.getElementById("d1").style.height="160px";
}
div
{
background-color:RGB(177,0,0);
color:white;
font-size:large;
height:160px;
width:230px;
text-align:center;
line-height:150px;
}
<!DOCTYPE html>
<html>
<body>
<div onmouseover="chg()" onmouseout="chg2()" id="d1">Hover Over Me!</div>
</body>
</html>
TL;DR # Use CSS animations for simpler "one-shot" transitions, like toggling UI element states. Use JavaScript animations when you want to have advanced effects like bouncing, stop, pause, rewind, or slow down.
CSS has fairly good performance as it offloads animation logic onto the browser itself. This lets the browser optimize DOM interaction and memory consumption and most importantly, uses the GPU to improve performance. On the other hand, Javascript performance can range from reasonably faster to much slower than CSS.
To make an animation possible, the animated element must be animated relative to a "parent container". The container element should be created with style = "position: relative". The animation element should be created with style = "position: absolute".
You should check out the transition
property in CSS3.
Check the following links for more information:
function chg() {
document.getElementById("d1").innerHTML = "Great Job!";
document.getElementById("d1").style.width = "300px";
document.getElementById("d1").style.height = "200px";
}
function chg2() {
document.getElementById("d1").innerHTML = "Hover Over Me!";
document.getElementById("d1").style.width = "230px";
document.getElementById("d1").style.height = "160px";
}
div {
background-color: RGB(177, 0, 0);
color: white;
font-size: large;
height: 160px;
width: 230px;
text-align: center;
line-height: 150px;
transition: all .5s linear;
}
<div onmouseover="chg()" onmouseout="chg2()" id="d1">Hover Over Me!</div>
The best way to accomplish this would be to do a CSS3 transition when the width changes.
Such as the following:
div
{
transition:width 1s ease-in-out;
}
with CSS3 you don't need javascript to create that effect..
div {
background-color:RGB(177,0,0);
color:white;
font-size:large;
height:160px;
width:230px;
text-align:center;
line-height:150px;
transition:all 1s;
}
div:hover {
height:200px;
width:300px;
}
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