kien64
kien64

Reputation: 15

saving both checkbox and audio state to local storage

I am trying to save to local storage the state of both a checkbox (checked/unchecked) and audio (play/pause). The default state of the checkbox is checked and audio is playing (looping) as seen in the code below.

So if the checkbox is checked, audio is playing and both should be saved to local storage (checkbox checked and audio playing).

Else if the checkbox is unchecked, audio is paused and both should be saved to local storage (checkbox unchecked and audio paused).

The problem I have is with saving the state of the checkbox and audio after it's been checked again.

Steps in reproducing the issue: 1) uncheck checkbox > audio stops > refresh browser > works 2) check checkbox > audio playing > refresh browser > not working, checkbox unchecked and audio not playing

Here is the javascript:

if (window.localStorage.getItem("musicState") != null) {
    var music = window.localStorage.getItem("musicState");
    if (music == "true") {
        status = 'pause';
        $("audio").trigger(status);
    }
    else {
        status = 'pause';
        $("audio").trigger(status);
        $("input:checkbox[name='music']").removeAttr("checked");
    }
}


$("input:checkbox[name='music']").click(function () {
    var visMusic = "play";
    if (status == 'pause') {
        status = 'play';

    } else {
        status = 'pause';
    }
    $("audio").trigger(status);

    window.localStorage.setItem("musicState", visMusic)

});

here is the HTML:

<audio autoplay loop>
    <source src="audio/music.mp3" type="audio/mpeg">
</audio>
<label><input type="checkbox" name="music" checked></label>

Upvotes: 0

Views: 131

Answers (1)

Ashley
Ashley

Reputation: 917

In your checkbox's click callback you are setting visMusic as "play". You never update it before storing it in localStorage as "musicState". This means that no matter what you do, "musicState" is always going to equal "play".

In your if-statement at the top (where you are retrieving from localStorage) you are testing if what you stored is "true". It is not, and never will be, because it is always "play". Your code is always going to your else which pauses the music and unchecks the box.

Here is an updated version that should work:

if (window.localStorage.getItem("musicState") != null) {
    var music = window.localStorage.getItem("musicState");
    if (music == "true") {
        status = 'play';
        $("audio").trigger(status);
    }
    else {
        status = 'pause';
        $("audio").trigger(status);
        $("input:checkbox[name='music']").removeAttr("checked");
    }
}

$("input:checkbox[name='music']").click(function () {
    var visMusic = "false";
    if (status == 'pause') {
        status = 'play';
        visMusic = "true";
    } else {
        status = 'pause';
    }
    $("audio").trigger(status);

    window.localStorage.setItem("musicState", visMusic)
});

Upvotes: 1

Related Questions