Transition does not work in Javascript

Asked

Viewed 270 times

4

The 'Transition' option does not work in this code

What’s wrong?

If you can explain where I went wrong

I wanted her to come out 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>

2 answers

3


Several reasons for this not to work:

  • transitions of display: none; for 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 first it has to be on the page.

  • the rule transition: all3s must be already defined in the element and its initial values. Call transition only with the end 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 "show up where it is" you have to manipulate the display and the opacity one after the other:

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>

  • 1

    It would be like putting an animation in the attribute visibilty in the same situation as the question?

  • 1

    @Laérciolopes in this case I suggest you take a look here: https://answall.com/a/44684/129 O visibility behaves like the display. Either it is or it is not, it does not allow transitions.

  • 1

    Entedi Unaware of display information not working with Transition Entedi the 2 ways, but the second was what you wanted... Thank you...it was so simple

0

And if it were image?

I wanted the Transition or that some way exchange the images slowly...

<!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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.