I am trying to create a JavaScript function where when the user scrolls down the page at a certain point (800 px) my audio file plays. I do not know how to properly write the JavaScript but I believe it needs to incorporate an if statement. Can someone please help.
window.addEventListener('scroll', () => {
const play = document.querySelector('.play');
if (window.scrollY > 800) {
document.getElementById("playAudio").play();
}
});
*{
margin:0;
padding:0;
box-sizing: border-box;
}
section{
height: 100vh;
overflow: hidden;
}
.one{
background:brown ;
}
.two{
background: pink;
}
.three{
background:lightgreen ;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio on scroll</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<section class="one"></section>
<section class="two">
<div class="play">
<div id="playAudio">
<audio autoplay src="audio/myaudio.mp3"></audio>
</div>
</div>
</section>
<section class="three"></section>
<script src="index.js"></script>
</body>
</html>
2
Answers
You just need to make sure the if statement is inside the event listener function. You need to call the
play()
method on your audio element. Like:This will start playing the audio when you’ve scrolled more than 800px down the page.
You should put an if statement inside your listener function and check the current scroll amount.
Also, you should select the audio element and not its container.
In your example the maximum scroll possible is less than
800px
so I changed it to200px
for the example.Notice that this will get called for every scroll from 200px, if you need it to be called only once you can use a boolean to tell if the audio was already played or not;