Reputation: 3
Is it possible to animate only the opacity, and have it move in a direction across a div? Let's say from left to right?
Here is my code so far: just missing something that says Left, if it's even feasible:
$(document).ready(function() {
$('#box').mouseenter(function() {
$(this).animate({opacity: ".5"}, 500);
});
});
Upvotes: 0
Views: 2564
Reputation: 1861
You can use the CSS linear-gradient
property and then run an animation loop to vary where it changes. Here is a quick JS Fiddle showing the effect.
The basic idea is to set the CSS based on the animation progress. For example, using a white background fading to transparent, at 25% complete you'd have:
background: linear-gradient(to right,
rgba(255, 255, 255, 1) 0%,
rgba(255, 255, 255, 0.25) 25%,
rgba(255, 255, 255, 0) 100);
And on subsequent steps change the 0.25
and 25%
to the current progress percent. The Javascript from the fiddle looks like:
var $child = $('#child');
var steps = 100;
var interval = 20;
var step = 0;
var animationStep = function() {
if( step >= steps ) return;
++step;
var progress = step / steps;
var progressPercent = Math.floor(progress*100) + '%';
$child.css('background',
'linear-gradient(to right, ' +
'rgba(255,255,255,1) 0%, ' +
'rgba(255,255,255,' + progress + ') ' + progressPercent + ', ' +
'rgba(255,255,255,0) 100%)'
);
setTimeout(animationStep, interval);
};
animationStep();
You could adapt this to be more general use in terms of colors, reusing on multiple elements, etc, but this should give you the basic idea.
Upvotes: 1
Reputation: 11
<head>
<meta charset="utf-8">
<title>Animation</title>
<script src="js/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="mydiv" style="height:20px; width:49px; opacity:0.5; background-color:green;">
</div>
<script>
$('#mydiv').hover(
function(){
$(this).animate({height:40,width:200,opacity:1});
},
function(){
$(this).animate({height:20,width:100,opacity:0.5});
}
);
</script>
</body>
Upvotes: 0