Javascript Animation Appear div from the top

I would like to make a animation feature using Javascript and CSS
I want a div to appear from the top and then transition it to the full height
so start: height = 0 and end: height 200px (for example)

I know this Feature can be easly done with Jquery But i want to do it with javascript
So I can learn more using javascript.

Could it be worth it?

html:

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    
    <title>Document</title>
</head>
<body>
    <button id="btn">Show</button>

    <div id="div">
        &nbsp;
    </div>
    
    <script src="index.js"></script>
</body>
</html>

js:

var div = document.getElementById('div');
var btn = document.getElementById('btn');
btn.addEventListener('click', ()=>{ 
    let h = '200px';
    if (div.style.height === '200px') h = '0px';
    div.style.height = h;
});

css:

div{
    background-color: red;
    width: 200px;
    height: 0px;
    transition: all .5s;
}

It could be further refined, I think it does what you ask, so I’ll leave it to you

1 Like

I have edited the answer the code I had written was very bad, this is better.

1 Like

Another way to do it.

html:

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    
    <title>Document</title>
</head>
<body>
    <button id="btn">Show</button>

    <div id="div">
        &nbsp;
    </div>
    
    <script src="index.js"></script>
</body>
</html>

css:

div{
    background-color: red;
    width: 200px;
    height: 0px;
    transition: all .5s;
}

.big{
    height: 200px;
}

js:

var div = document.getElementById('div');
var btn = document.getElementById('btn');

btn.addEventListener('click', ()=>{ 
    div.classList.toggle('big');
});

1 Like

it works great sir thank you very much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.