Francisco Romero
Francisco Romero

Reputation: 13189

How can I animate an element changing its opacity at the same time?

I would like that an element makes an animation from left to right changing its opacity from 0 to 1.

I have animated the element but I cannot change its opacity at the same time.

This is the code that I have by the moment:

$("#moveIt").animate({left:0, opacity:"show"}, 1500);
#moveIt{
  position: relative;
  left: 200px;
  height: 300px;
  width: 300px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moveIt">
  <span>This is the div that I want to move</span>
</div>

I know that there is a function on JQuery called fadeTo but I do not know how to combine it with animate function to change the opacity of the element at the same time I animate the element.

I can wrap the animate function with fadeTo function but it changes the opacity of the element before the animate function fires, not at the same time, as I need.

How can I change the opacity of the element at the same time I animate it?

Thanks in advance!

Upvotes: 0

Views: 100

Answers (3)

Kalimah
Kalimah

Reputation: 11437

You can replace .animate() with a more CSS solution.

Example:

$(document).ready(function() {
  $("#moveIt").addClass('animate');
});
.element {
  position: relative;
  left: 200px;
  height: 300px;
  width: 300px;
  background-color: red;
  transition: all 1.5s; /* change speed here (1.5s)*/
  opacity: 0;
}

 /* Values to animate to */
.animate {
  opacity: 1;
  left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moveIt" class='element'>
  <span>This is the div that I want to move</span>
</div>

Upvotes: 0

Deep
Deep

Reputation: 9794

The opacity property can take a value from 0.0 - 1.0.

http://www.w3schools.com/css/css_image_transparency.asp

Change

$("#moveIt").animate({left:0, opacity:"show"}, 1500);

To

$("#moveIt").animate({left:0, opacity:1}, 1500);

if you want to fade in then set opacity 0 on page load using css and change it to 1 using .animate()

$("#moveIt").animate({left:0, opacity: 1}, 1500);
#moveIt{
  position: relative;
  left: 200px;
  height: 300px;
  width: 300px;
  background-color: red;
  opacity : 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moveIt">
  <span>This is the div that I want to move</span>
</div>

Upvotes: 2

YSuraj
YSuraj

Reputation: 417

Initialize the opacity.

$("#moveIt").animate({left:0, opacity: 1}, 1500); // set opacity to 1
#moveIt{
  position: relative;
  left: 200px;
  height: 300px;
  width: 300px;
  background-color: red;
  opacity : 0; /* opacity to zero */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moveIt">
  <span>This is the div that I want to move</span>
</div>

Upvotes: 1

Related Questions