Animation is not smooth

3

Oops guys I have a div that is my site header, I want to hide it by clicking a button and making it appear when clicking another button. I can hide it and the movement is the way I want it, but when it comes to showing it back it does not show the same fluidity and the image does not stay on the screen, disappearing at the end.

function myMove() {
    var elem = document.getElementById("box-toogle"); 
    var pos = 0;
	var t = 0;
	var id = setInterval(frame, 5);
    function frame() {
        if (pos == 160) {
            clearInterval(id);
        } else {
            pos--; 
            elem.style.top = pos + 'px'; 
				t++;
        }
}

function myMove1() {
    var elem = document.getElementById("box-toogle"); 
    var pos = 150;
	var t = 0;
	var id = setInterval(frame, 5);
    function frame() {
        if (pos == 0) {
            clearInterval(id);
        } else {
            pos--; 
            elem.style.top = pos + 'px'; 
				t++;
        }
}
#box-toogle {
	width: 100%;
    height: 150px;
    position: relative;
}
<html>
  <head>
  </head>
<body>
<header id="box-toogle">texto</header>
 </body>
</html>

I am a beginner in javascript, if you can help me thank you

    
asked by anonymous 29.05.2016 / 03:21

1 answer

2

This type of animation should be done with CSS.

In this case you only need

#box-toogle {
    // ...

    top: 0px;
    transition: top 1s;
}

#box-toogle.escondido {
    top: -100px;
}

and when the element is clicked you add or remove this class escondido .

Example:

var header = document.getElementById('box-toogle');
header.addEventListener('click', function() {
    this.classList.toggle('escondido');
});
#box-toogle {
    width: 100%;
    height: 150px;
	border: 2px #ddf solid;
	font-size: 80px;
	
	top: 0px;
    position: relative;
    transition: top 1s;
}

#box-toogle.escondido {
    top: -100px;
}
<header id="box-toogle">texto</header>

jsFiddle: link

    
29.05.2016 / 08:49