Question

I'm using the following script for playing background music on a web page.

$(function()
    {
        var bgMusic = $('#audio-bg')[0],
            playing = true;

        bgMusic.addEventListener('ended', function() {
            this.currentTime = 0;
            if (playing) {
                this.play();
            }
        }, false);

        bgMusic.play();

        $('#toggle').click(function() {
            if (!bgMusic.paused) {
                bgMusic.pause();
                playing = false;
                $(this).css({backgroundPosition: '0 -21px'})
            } else {
                bgMusic.play();
                playing = true;
                $(this).css({backgroundPosition: '0 0'})
            }
        });
    });
<audio id="audio-bg">
    <source src="music/Something_for_Nothing_OST_-_Close_darkness_The.mp3">Update your browser for playing music</source>
</audio>
<a id="toggle" class="volume-icon" href="javascript:">Toggle</a>

The music plays and the toggle button works, but is it possible to let pages remember the user's mute/volume preference? For example: I visit the site, music will start playing automatically. I click the mute button to turn off the music, but if I refresh or go to the next page, the music will start playing again.

How can I make the website remember the user's volume/mute preference?

Was it helpful?

Solution

Use cookies. There's a plugin for jquery you can get. Here is a bit of code to get you started:

    var bgMusic = $('#audio-bg')[0],
        playing = true;

    bgMusic.addEventListener('ended', function() {
        this.currentTime = 0;
        if (playing) {
            this.play();
        }
    }, false);

    var cookieValue = $.cookie("forcemute");

    if(cookieValue == undefined){
        bgMusic.play();
    }
    else{
        playing = false;
    }

    $('#toggle').click(function() {
        if (!bgMusic.paused) {
            bgMusic.pause();
            playing = false;
            $(this).css({backgroundPosition: '0 -21px'})

            $.cookie("forcemute", 1);
        } else {
            bgMusic.play();
            playing = true;
            $(this).css({backgroundPosition: '0 0'})

            $.removeCookie("forcemute");
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top