Playing background sound on Squarespace

Blog

Check Out Useful Squarespace articles here

Playing background sound on Squarespace

Popular question on Squarespace Answers  is about adding some background music to page. This is not the best UX to autoplay something on pageload, but we may give a try.

Offcourse you can add Code Block to the page for this, but default Audio Block is far more comfortable.  And I will show how easy do this trick.

First of all - add Audio Block on the page and upload the file you want. 

Add audio on the page

Add audio on the page

After, go to Advanced Tab and add next code:

 
<script>
window.addEventListener('DOMContentLoaded', function() { //wait for document load
    var audio = document.querySelector('.sqs-audio-embed'); //select the audio block
    if (!Y.UA.mobile) { //it is not mobile
        var checkOnScroll = function() {
            if (window.pageYOffset > 200) {
                audio.pause();
            } else {
                audio.play();
            }
        };
        if (audio) {
            var url = audio.getAttribute('data-url'); //get the audio src
            Y.one(audio).ancestor('.sqs-block-audio').setStyle('display','none');
            audio = new Audio(url);
            window.addEventListener('scroll', checkOnScroll); //listen for window scroll and toggle audio state
            checkOnScroll();
        }
    }
})
</script>
 

As we added code to Page Injection Tab - background sound will start only on this page.

Code SnippetsMichael Mashai