Javascript - Button & Sound

Written by: Mo Al-kaf | Posted on:

I had noticed that when scrolling with the mouse wheel the whole canvas would move slightly. i thought this did not like nice on the website. The scrolling was enabled on the webpage. I read in the reference there was an option to lock scrolling when the event is called.

Screenshot 2019-04-26 at 10.06.36 pm.png

however, when enabling this option you could not scroll the text box. i searched for available options to add a button to toggle this option.

I can create a button in P5.js that can use to toggle this event. i used this following code:

buttonfly = createButton("Start Flying"); buttonfly.position(windowWidth - 150, 110);

Using windowWidth I can responsively position the button to be in the same place at any window width. I also added this code in the windowResize to the button are redrawn anytime teh visitor changed the window size. This made the website more responsive to size adjustment.

function windowResized() { resizeCanvas(windowWidth, windowHeight); buttonfly.position(windowWidth - 150, 110); }

To add interactivity to the button i added a function to toggle the scrolling so the event can be called when the user clicks on the button:

let flying = true; function toggleFlying () { flying = !flying; if (flying == true) { buttonfly.html("Start Flying"); } else { buttonfly.html("Stop Flying")} }

so anytime the user clicked on the button the scrolling would be enabled or disabled. buttonfly = createButton("Start Flying"); buttonfly.mousePressed(toggleFlying);

this worked nicely as if the visitor wanted to "fly" at a faster speed they could lock the scroll and scroll freely with the stars.

When i tested this out I thought maybe some music would help the atmosphere of flying through the stars. However, I noticed that many of the web browsers block audio media without any user interaction. I thought to add another button to toggle playing and pausing of the music at the discretion of the user.

buttonMp3.mousePressed(togglePlaying); function togglePlaying () {

if (!song.isPlaying()) { song.play(); song.setVolume(0.3); buttonMp3.html("Stop Sound") }else{ song.pause(); buttonMp3.html("Start Sound")

I just needed to add the MP3 file to the assets of the webpage on the hosting site.

This where the last things that i added to the website to finish the experience.