Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
How to make sound play only on current page? Java Script

I am a graphic designer building website in Cargo Collective. I want to make sound play when user clicks the mouse or tap the screen. I use this code:

<script>
function MouseSound() {
    var fileUrl = "https://files.cargocollective.com/c1242413/sound-1.mp3";
    var audio = new Audio(fileUrl);
    audio.play();
}

window.addEventListener('click', MouseSound , false);
</script>

I use function MouseSound() to do it. But I have a problem — the sound keeps playing on the next website page on click, even if there's no script in it. I want to play sound only on pages with the script.

I guess it's because window thing? Or it's script just stays in cache? How it's possible to play different sounds on different pages OR just play them only on pages, that have the script? Thank you.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Yes. You are right. The problem is occurring because of the window thing. So, in the other webpage, you can add this script:

<script>
function EmptyMethod() {}

window.addEventListener('click', EmptyMethod , false);
</script>
about 4 years ago · Juan Pablo Isaza Report

0

Just use document instead of window. document refers to this webpage or DOM. You could do:

document.addEventListener("mouseleave", stopSound);

This will fire whenever you leave the page, go to a new tab, leave the browser window, close the browser window. You can make a stopSound() function that pauses the sound like so:

function stopSound() {
  audio.pause();
}

You can also mute the sound with audio.muted = true, but this will not pause the sound and sound will play in the background but we cannot hear it.

Now resume the sound with audio.play(). you can do:

document.addEventListener("mouseenter", playSound);

function playSound() {
  audio.play();
}

Just play with the code and see what suites your need.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!