transition does not work in Javascript

4

The 'transition' option does not work in this code

What is wrong?

If you can explain where I went wrong

I wanted it to come up slowly

<!DOCTYPE html>
<html>
<head>
	<title>teste</title>
<style type="text/css">
	
	div{
		width: 500px;
		height: 100px;
		border:5px solid blue;
		display: none;
}
</style>
</head>
<body>
<script type="text/javascript">
	
	function chamar(){
		document.getElementById("aparecer").style.display="block"
		document.getElementById("aparecer").style.transition='all 3s'
}

</script>
<p onClick="chamar()">chamar</p>
<div id="aparecer"></div>
</body>
</html>
    
asked by anonymous 18.08.2017 / 21:58

2 answers

3

Several reasons this does not work:

  • Transitions from display: none; to display: block; are not possible. The element can only transition if it is already on the page. You can give a margin of 10ms, but you must first be on the page.

  • The transition: all3s rule must already be defined in the element and its initial values. Calling transition with only the final value can produce unexpected results in some browsers

My suggestion is to do this with a CSS class only:

function chamar() {
  var div = document.getElementById("aparecer");
  div.classList.add('chamada');
}
div {
  width: 0;
  height: 0;
  border: 0;
  opacity: 0;
  transition: all 3s;
}

div.chamada {
  width: 500px;
  height: 100px;
  border: 5px solid blue;
  opacity: 1;
}
<p onClick="chamar()">Clica-me!</p>
<div id="aparecer"></div>

If you want to make "appear where you are" you have to manipulate display and opacity one after another:

function chamar() {
  var div = document.getElementById("aparecer");
  div.style.display = 'block';
  setTimeout(function() {
    div.style.opacity = 1;
  }, 50);
}
div {
  width: 500px;
  height: 100px;
  border: 5px solid blue;
  display: none;
  opacity: 0;
  transition: opacity 3s;
}
<p onClick="chamar()">Clica-me!</p>
<div id="aparecer"></div>
    
18.08.2017 / 22:04
0

What if it were an image?

I wanted the transition or that somehow change the images slowly ... in transition

<!DOCTYPE html>
<html>
<head>
	<title>teste</title>
</head>
<body>
<script type="text/javascript">
	
	function mudar(){
		document.getElementById("img").src = "imagem 2.jpg"
	}

</script>

<img id="img" src="imagem 1.jpg" onclick="mudar()">


</body>
</html>
    
19.08.2017 / 18:31