James Wilson James Wilson - 3 months ago 7
jQuery Question

Use of global variable not working within .each function

Here is my script I am using:

<script type="text/javascript">
$(document).ready(function () {
var autoFlip = true;
$(document).on('click', '.cardFlip', function () {
$(this).closest('.flip-container').toggleClass('flip');
});

$("#auto_flip").change(function () {
if (autoFlip) {
autoFlip = false;
}
else {
autoflip = true;
}
});

// only flip the containers given the autoFlip class
$(".autoFlip").each(function (i) {
if (autoFlip) {
var el = $(this);
setTimeout(function () {
setInterval(function () {
el.closest('.flip-container').toggleClass('flip');
}, 5000);
}, 500 * i);
}
});

});

</script>


By default I have 4 boxes on my dashboard that automatically flip to reveal different content every 60 seconds. I'm trying to add a button that can turn this off for those users who wish to manually flip them.

However setting up my global
autoFlip
and setting it to
false
via a
click
#auto_flip
doesn't work. The variable is correctly set to
false
. but the flip keeps happening. Any idea why the
.each
is not caring if the autoFlip variable is changed?

Here is my button that i set to maketh variable false.

<input id="auto_flip" class="auto_flip" type="checkbox" checked data-on="Auto
Flip On" data-off="Auto Flip Off" data-toggle="toggle" data-onstyle="primary">

Answer

You're testing autoFlip when you start the timer, not when the timer code runs.

    $(".autoFlip").each(function (i) {
        var el = $(this);
        setTimeout(function () {
            setInterval(function () {
                if (autoFlip) {
                    el.closest('.flip-container').toggleClass('flip');
                }, 5000);
            }, 500 * i);
        }
    });

Also, your code to switch autoFlip can be simplified to:

autoFlip = !autoFlip;