My webpage features two jQuery effects applied to a <div>
. Using the animate()
function, I move it left and right, while utilizing fadeTo()
to fade it out when the mouse is not hovering over the <div>
.
To prevent multiple fading effects caused by quick mouse movements, I attempted using the jQuery stop()
function like so:
$("myDiv").stop().fadeTo(speed, opacity, callback);
However, this also halts my animation which is undesired. Once started, I want the animation to complete uninterrupted. Is there a way to achieve this without encountering flickering fading issues?
A reference in the jQuery documentation for stop() caught my attention:
Starting from jQuery 1.7, providing the first argument as a string allows stopping only animations within that specific queue.
This appeared promising until I tried assigning the fadeTo
effect to a named queue. While easily achievable with animate()
through options specified in the animate() jQuery documentation, no similar option is present in the fadeTo() jQuery documentation. Oddly enough, options to specify queues exist for fadeIn()
, fadeOut()
, and fadeToggle()
but not for fadeTo()
.
Am I overlooking something? Is there an alternate method to accomplish my objective?
Edit: Below is a streamlined version of my code to highlight the issue.
<div id="div1">
<div id="div2">
<div id="div3">
<div id="div4">
</div>
</div>
<button id="myButton" onclick="doACoolAnimation()" ></button>
</div>
</div>
The JavaScript sequence used for fading includes:
$('#div1').mouseenter(function() {
fadeElementTo('div1', 500, 1);
}).mouseleave(function() {
fadeElementTo('div1', 500, 0.5);
});
Here's the straightforward fadeElementTo()
function:
function fadeElementTo(eid, speed, opacity, callback) {
$("#" + eid).stop().fadeTo(speed, opacity, callback);
}
Clicking the button initiates an animation on the same div
previously faded, by shifting it left or right smoothly.
function doACoolAnimation() {
var hiddenState = GLOBAL_VAR.hiddenState;
// Make div visible if currently hidden
if (hiddenState == null || hiddenState == 1) {
GLOBAL_VAR.hiddenState = 0;
$("#div1").animate({
left: "0px"
}, 1500);
}
// Hide div otherwise
else {
GLOBAL_VAR.hiddenState = 1;
$("#div1").animate({
left: "-800px"
}, 1500);
}
}