Konstantinos Koletsas Konstantinos Koletsas - 6 months ago 12
jQuery Question

JavaScript: Variable always returns false

I wrote the following script to store the value of the variable "muted_status" and then pass it into a cookie but it seems like the variable always has a false value.

var muted_status = false;
$('#jp_container_1').on("click", function() {
setTimeout(function() {
if ($('#jp_container_1').hasClass("jp-state-muted")) {
var muted_status = true;
} else {
var muted_status = false;
}
}, 1000);
$.cookie('jp_mute', muted_status, { expires: 7, path: '/'});
});

Answer

There are two problems here. First, you're re-declaring a muted_status variable multiple times, which means that the variable you set in your setTimeout function is not the same as the one used by the call to $.cookie. Second, and most importantly, the call to $.cookie is happening synchronously, immediately after you set the timeout, whereas the muted_status is being set one second later.

Perhaps something like this is what you're going for?

function setMutedStatus(mutedStatus) {
    $.cookie('jp_mute', mutedStatus, { expires: 7, path: '/'});
}
setMutedStatus(false);
$('#jp_container_1').on("click", function() {
    setTimeout(function() {
        var mutedStatus = $('#jp_container_1').hasClass("jp-state-muted");
        setMutedStatus(mutedStatus);
    }, 1000);
});

This begins by setting the cookie to muted, but it may then set it to something else one second later. If your intent is to check the muted status every second, you'll want to use setInterval instead of setTimeout.

Comments