Can you target an element to its dynamically changing opacity?
By using the function in jQuery, along with my HTML and CSS, I have a series of different colored divs that change their opacity to make it look like the opaque div is moving from left to right. I want the user to be able to press the red button to stop the animation in a square of their choice. Right now I can get the animation to stop (albeit after it has finished animating in the queue), but I am having trouble getting the square with its opacity at 1 (at the time the button is clicked) while staying at opacity 1. Any help would be greatly appreciated.
Here is a jsfiddle http://jsfiddle.net/seifs4/krm6uenj/
$(document).ready(function () {
$.fn.extend({
brighten: function(){
$(this).fadeTo(150, 1);
}
});
$.fn.extend({
fade: function(){
$(this).fadeTo(150, 0.2);
}
});
function animateSequence() {
$('.game-square').each(function (i) {
$(this).delay((i++) * 145).brighten();
$(this).delay((i++) * 5).fade();
});
}
animateSequence()
var interval=setInterval(animateSequence, 1700);
$('#red-button').click(function(){
$('.game-square').each(function(){
if ($('.game-square', this).not().css('opacity') == 0.2){
$(this).css('opacity', '1');
}
});
clearInterval(interval);
});
});
source to share
I'll take a different and less complicated approach. It probably has even better performance.
Demo http://jsfiddle.net/LkatLkz2/8/
This is all the code. I am using css effect for animation and class changing opacity.
var sqrs = $('.game-square'),
len = sqrs.length,
i=0,
looping = true;
setInterval(function(){
if (!looping) return;
sqrs.removeClass('full').eq(i).addClass('full');
i = ++i % len;
},400);
$("#red-button").click(function () {
looping = !looping;
});
source to share
You may need something like this:
function animateSequence(){
this.current = 0;
this.squares = $(".game-square");
this.animate = function(){
this.squares.eq(this.current).fadeTo(150, 1, function(){
$(this).fadeTo(150, 0.2)
});
this.current = this.current >= this.squares.length - 1 ? 0 : this.current + 1;
};
this.start = function(){
this.running = setInterval(this.animate.bind(this), 150)
};
this.stop = function(){
this.running = clearInterval(this.running);
this.squares.eq(this.current).stop().css("opacity",1);
alert("Current color: " + this.squares.eq(this.current).attr("class"))
}
}
This is the advantage of working with objects, the way is very readable, simple and orderly.
source to share
The jQuery.stop () function helps to stop the animation. I know this is not the best solution for your problem because your opacity stays "1" for only a short time.
$('#red-button').click(function(){
clearInterval(interval);
$('.game-square').stop();//this stop the animation
$('.game-square').each(function(){
if ($(this).not().css('opacity') > '0.2'){// I changed this logic
$(this).css('opacity', '1');
}
});
});
source to share