arshivbastian / vue

a teamwork for vue
0 stars 0 forks source link

add sounds to events #11

Open arshivbastian opened 5 years ago

arshivbastian commented 5 years ago

welcome to this tutorial , in most apps you need to play a sound effect on click , hover and etc ... . I am using the result from #10 read it to get what we are doing here :

first you need to find sounds that you need , unfortunately many of providers are selling these stuff (cruel!) but I found this website , thanks to them !

now we need to define our sounds with audio tag :

<audio id="hover1" :src= "require('../assets/sounds/hover1.mp3')" ></audio>
<audio id="hover2" :src= "require('../assets/sounds/hover2.mp3')" ></audio>
<audio id="click" :src= "require('../assets/sounds/click.mp3')" ></audio>

so as you can see I have three mp3 sounds that named them hover , hover2 , click .

after this we need to use them in our function hover1 is for entrance of friendinfo div

 leftoright(hovered) {
        hovered.target.style.marginLeft = "0px" ;
        var hover1 = document.getElementById("hover1");
        const playPromise = hover1.play();
        if (playPromise !== null){
            playPromise.catch(() => { hover1.play(); });
            return false ;
        }
      },

hover2 is to for exit of friendinfo div

righttoleft(hovered) {
        hovered.target.style.marginLeft = "-280px" ;
        var hover2 = document.getElementById("hover2");
        const playPromise = hover2.play();
        if (playPromise !== null){
            playPromise.catch(() => { hover2.play(); })
        }
      },

click is for click on friendinfo div

keepactive(clicked , clickedname) {
        $(".friendsinfo").css('box-shadow','0px 0px 0px 0px');
        clicked.target.style.boxShadow = "9px 2px 25px 7px rgba(171,164,40,1)";
        var click = document.getElementById("click");
        const playPromise = click.play();
        if (playPromise !== null){
            playPromise.catch(() => { click.play(); })
        }
        for (var counter=0 ; counter<this.allies.length ; counter++){
          if (this.allies[counter].name == clickedname ) {
              console.log(this.allies[counter].name);
              this.chatname = this.allies[counter].name ;
              break;
          }
        }
      },

the code related to audio is :

        var click = document.getElementById("click");
        const playPromise = click.play();
        if (playPromise !== null){
            playPromise.catch(() => { click.play(); })
        }

this code will get the tag we create in html part with id of click , then tries to play it , mostly in first attempt .play() returns null and you will see the Uncaught (in promise) DOMException in console . so we are using the if to retry to play it !

this is it , easy peasy !