Bruno Filipe
Bruno Filipe

Reputation: 33

Javascript/HTML5 - Save mute on localstorage

I'm creating 5 games with javascript and html5 and I'm using sound. I have a mute button that activates the function down bellow. Thing is, I want to make so that if I press the mute button and I move to another page, it will still be muted, but I can't seem to figure out how to integrate it in this function. If someone could help me out by editing the code, I'd really apreciate it :D

function init(){
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;

    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);

function mute(){
    if (audio.muted){
        audio.muted = false;
        document.getElementById("mutebtn").src = "img/soundON.png";
    } else {
        audio.muted = true;
        document.getElementById("mutebtn").src = "img/soundOFF.png";


        }

    }
}

Upvotes: 1

Views: 302

Answers (2)

Trash Can
Trash Can

Reputation: 6824

Modify your function like this

function init() {
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;
    var muteState = localStorage.getItem('muteState');
    if (!muteState || muteState !== 'true') {
        audio.muted = false;
        document.getElementById("mutebtn").src = "img/soundON.png";
    }
    else {
        audio.muted = true;
        document.getElementById("mutebtn").src = "img/soundOFF.png";
    }
    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);

    function mute() {
        if (audio.muted) {
            audio.muted = false;
            document.getElementById("mutebtn").src = "img/soundON.png";
        } else {
            audio.muted = true;
            document.getElementById("mutebtn").src = "img/soundOFF.png";
        }
        localStorage.setItem('muteState', String(audio.muted));
    }

}

Upvotes: 1

Jerhemy
Jerhemy

Reputation: 590

Add the muted value to your localStorage in your 'mute' method.

function mute(){
        ...
        audio.muted = false;
        localStorage.setItem('muted', 'false');
    } else {
        audio.muted = true;
        localStorage.setItem('muted', 'true');
    }
}

}

Then on your init retrieve the localStorage value or default to false if it wasn't set prior.

function init(){
    audio = new Audio();
    audio.src = "sound/paint_Music.mp3";
    audio.loop = true;
    audio.autoplay = true;
    var isMuted = (localStorage.getItem("muted") && localStorage.getItem("muted") == 'true') || false

    audio.muted = isMuted;
    mutebtn = document.getElementById("mutebtn");
    mutebtn.addEventListener("click", mute);
}

Upvotes: 0

Related Questions