0
votes

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?

1
Hi, what do you mean by "is it real"? Do you mean "possible"?JSideris
if you want you can do that for one sessionashishmaurya
You will need cookies to remember the mute status in browsersGodinall

1 Answers

1
votes

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");
        }
    });
});