Categories
Vue 3 Projects

Add an Audio Player with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a video player with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create audio-player

and select all the default options to create the project.

Create the Audio Player

We can create the audio player by writing:

<template>
  <input
    type="range"
    min="0"
    max="100"
    step="1"
    v-model="seekValue"
    @change="onSeek"
  />
  <audio
    src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
    ref="audioPlayer"
    @timeupdate="onPlaying"
  >
    Your browser does not support the
    <code>audio</code> element.
  </audio>
  <p>{{ currentTime }}</p>
  <div>
    <button @click="play">play</button>
    <button @click="pause">pause</button>
    <button @click="stop">stop</button>
    <button @click="setSpeed(0.5)">0.5x</button>
    <button @click="setSpeed(1)">1x</button>
    <button @click="setSpeed(1.5)">1.5x</button>
    <button @click="setSpeed(2)">2x</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      currentTime: 0,
      seekValue: 0,
    };
  },
  methods: {
    play() {
      this.$refs.audioPlayer.play();
    },
    pause() {
      this.$refs.audioPlayer.pause();
    },
    stop() {
      const { audioPlayer } = this.$refs;
      audioPlayer.pause();
      audioPlayer.currentTime = 0;
    },
    setSpeed(speed) {
      this.$refs.audioPlayer.playbackRate = speed;
    },
    onPlaying() {
      const { audioPlayer } = this.$refs;
      if (!audioPlayer) {
        return;
      }
      this.currentTime = audioPlayer.currentTime;
      this.seekValue = (audioPlayer.currentTime / audioPlayer.duration) * 100;
    },
    onSeek() {
      const { audioPlayer } = this.$refs;
      const seekto = audioPlayer.duration * (this.seekValue / 100);
      audioPlayer.currentTime = seekto;
    },
  },
};
</script>

We have a range input that we can slide around to change the seekValue ,

We bound it to seekValue with v-model .

Also, we attach a change event handler to the input that changes the currentTime of the audio element to seek the audio.

The audio element has the audio we want to play.

We listen to the timeUpdate event so we can get the current time.

We assign a ref to it so we can manipulate it later.

Below that, we display the currentTime .

And then we have a few buttons to let us play, pause, stop, and change the speed of the audio.

Below the template, we have the data method with the currentTime and seekValue reactive properties returned.

The play method gets the audio player element from the ref and call play to play the audio.

The pause method gets the audio player element from the ref and call pause to pause the audio.

The stop method pauses the audio and set the currentTime to 0 to reset the audio playback back to the beginning.

setSpeed lets us set the speed by changing the playbackRate property.

The onPlaying method is called when the timeUpdate event is emitted.

We set the this.currentTime reactive property to the currentTime property of the audioPlayer .

Also, we update the seekValue so that it’s in sync with the currentTime .

This will update the range slider to be in sync with the currentTime .

Finally, we have the onSeek method that’s run when the change event is emitted by the range input, which is done when we’re done moving the slider.

We get the seekValue reactive property and to compute the seekTo value by multiplying that by the duration and dividing by 100.

Then we set that to the currentTime to change the current time.

Conclusion

We can add an audio player with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Add a Video Player with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a video player with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create video-player

and select all the default options to create the project.

Create the Video Player

We can create the video player by writing:

<template>
  <video width="320" height="240" ref="videoPlayer">
    <source
      src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4"
      type="video/mp4"
    />
    Your browser does not support the video tag.
  </video>
  <div>
    <button @click="play">play</button>
    <button @click="pause">pause</button>
    <button @click="stop">stop</button>
    <button @click="setSpeed(0.5)">0.5x</button>
    <button @click="setSpeed(1)">1x</button>
    <button @click="setSpeed(1.5)">1.5x</button>
    <button @click="setSpeed(2)">2x</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    play() {
      this.$refs.videoPlayer.play();
    },
    pause() {
      this.$refs.videoPlayer.pause();
    },
    stop() {
      const { videoPlayer } = this.$refs;
      videoPlayer.pause();
      videoPlayer.currentTime = 0;
    },
    setSpeed(speed) {
      this.$refs.videoPlayer.playbackRate = speed;
    },
  },
};
</script>

We have the video element with a ref assigned to it.

width and height sets the dimensions of the video.

The source element has the video source.

We set it to the URL to an MP4 clip that we want to play.

Below that, we add buttons to let us play, pause, and stop the video.

We also have buttons that let us change the playback speed.

Then below that, we add some methods that are called when we click on buttons.

The play method lets us play the video by getting the videoPlayer ref with this.$refs.videoPlayer and calling the play method on the returned video element.

The pause method is similar. We get the videoPlayer ref which has the element and call pause on it to pause the video.

A video element has no method to stop a video. But we can implement that by pausing it and resetting the currentTime to 0.

To set the speed of the video, we can set the playbackRate property.

0.5 is half the normal speed.

And anything above 1 is faster than normal speed.

Conclusion

We can add a video player easily into our web app with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create an Accordion Component with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an accordion component with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create accordion-component

and select all the default options to create the project.

Create the Accordion Component

To create the accordion component, we write:

<template>
  <div v-for="c of contents" :key="c.title">
    <div class="title" @click="c.expanded = !c.expanded">
      <div>
        <b>{{ c.title }}</b>
      </div>
      <div>
        <span v-if="c.expanded">&#x2191;</span>
        <span v-else>&#x2193;</span>
      </div>
    </div>
    <div class="description" v-if="c.expanded">
      {{ c.description }}
    </div>
  </div>
</template>

<script>
const contents = Array(10)
  .fill()
  .map((_, i) => {
    return {
      title: `title ${i}`,
      description: `description ${i}`,
      expanded: false,
    };
  });

export default {
  name: "App",
  data() {
    return {
      contents,
    };
  },
};
</script>

<style scoped>
.title {
  cursor: pointer;
  display: flex;
  justify-content: space-between;
}

.title,
.description {
  border: 1px solid black;
  padding: 5px;
}
</style>

We start by adding the elements for the accordion in the templaye.

We use the v-for directive to render the contents array into an accordion.

The key is set to the c.title property, which is unique.

In the inner div, we attached a click listener with the @click directive.

The click listener toggles the expanded property.

Inside it, we render the c.title property and show the down arrow if it’s not expanded, which is when c.expanded is false

And we show the up arrow when c.expanded is true .

c.description is rendered in the div below the title div.

It’s only shown with c.expanded is true .

Below that, we have the contents array to add some content to show.

In the data method, we return an object with the contents reactive property created from the contents array.

In the style tag, we have the title class selector’s styles set to cursor: pointer to set to a hand cursor.

display set to flex to enable flex layout.

This lets us use justify-content set to space-between to display the 2 divs at the left and right ends of the title div.

Then finally, we set the border and padding on the divs with the title and description classes styles.

We add a border and padding to these divs.

Now when we click on the title divs, we see the description divs toggled on and off.

Conclusion

We can create an accordion component easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Tooltip with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a tooltip with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create tooltip

and select all the default options to create the project.

Create the Tooltip

To create the tooltip, we write:

<template>
  <div id="container">
    <button @mouseover="onHover">hover me</button>
    <div
      id="tooltip"
      :style="{ top: `${clientY}px`, left: `${clientX}px` }"
      v-if="show"
      @mouseout="show = false"
    >
      tooltip
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      show: false,
      clientX: 0,
      clientY: 0,
    };
  },
  methods: {
    onHover(e) {
      const { clientX, clientY } = e;
      this.show = true;
      this.clientX = clientX;
      this.clientY = clientY;
    },
  },
};
</script>

<style scoped>
#container {
  width: 95vw;
  height: 95vh;
  align-items: center;
  display: flex;
  justify-content: center;
}

#tooltip {
  border: 1px solid black;
  padding: 5px;
  position: absolute;
  background-color: white;
}
</style>

We have a button that triggers the tooltip when we hover over it.

The button has the @mouseover directive to run the onHover method.

onHover sets this.show to true to show the tooltip.

It also sets the clientX and clientY reactive properties to set the position of the tooltip.

Below that, we have a div with ID tooltip .

The style prop has an object that has the top and left properties to set the position of the tooltip according to the position of the mouse.

In the script tag, we have the data method that returns an object with the reactive properties and their initial values.

In the style tag, we have the styles for the container div to center its content horizontally and vertically.

We center the content horizontally with justify-content .

align-items set to center center content vertically.

display: flex enables flex layout which lets us use align-items and justify-content .

The div with ID tooltip has styles to set the border, padding, and makes the position absolute .

background-color is set to white to make the background white instead of transparent.

Now when we hover over the button, we see the tooltip displayed where the mouse pointer is.

Conclusion

We can create a tooltip easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Hi-Low Card Game with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a hi-low card game with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create hi-low-game

and select all the default options to create the project.

Create the Hi-Low Card Game

To create the hi-low game, we write:

<template>
  <form @submit.prevent="draw">
    <select v-model="guess">
      <option>lower</option>
      <option>higher</option>
    </select>
    <button type="submit">guess</button>
  </form>
  <p>score: {{ score }}</p>
  <p>last drawn card</p>
  <img
    v-if="drawnCards[drawnCards.length - 2]"
    :src="`https://tekeye.uk/playing_cards/images/svg_playing_cards/fronts/${
      drawnCards[drawnCards.length - 2]
    }.svg`"
  />
  <p>currently drawrn card</p>
  <img
    v-if="drawnCards[drawnCards.length - 1]"
    :src="`https://tekeye.uk/playing_cards/images/svg_playing_cards/fronts/${
      drawnCards[drawnCards.length - 1]
    }.svg`"
  />
</template>

<script>
const suits = ["diamonds", "clubs", "hearts", "spades"];
const values = ["ace", 2, 3, 4, 5, 6, 7, 8, 9, 10];
const cards = [];
for (const s of suits) {
  for (const v of values) {
    cards.push(`${s}_${v}`);
  }
}
export default {
  name: "App",
  data() {
    return {
      score: 0,
      cards: [...cards].sort(() => Math.random() - 0.5),
      drawnCards: [],
      guess: "lower",
    };
  },
  methods: {
    draw() {
      const drawnCard = this.cards.pop();
      this.drawnCards.push(drawnCard);
      const indexLastCard = cards.indexOf(
        this.drawnCards[this.drawnCards.length - 2]
      );
      const indexDrawnCard = cards.indexOf(
        this.drawnCards[this.drawnCards.length - 1]
      );
      if (
        (indexLastCard < indexDrawnCard && this.guess === "higher") ||
        (indexLastCard > indexDrawnCard && this.guess === "lower")
      ) {
        this.score++;
      }
    },
  },
};
</script>

In the template, we have the form element with a select dropdown to let us pick whether the next card is higher or lower than the last drawn card.

The @submit directive lets us listen to the submit event, which is triggered when we click on a button with type set to submit .

The prevent modifier lets us prevent server-side submission and do client-side submission instead.

The score is displayed below the form.

And we display the last drawn card and the currently drawn card’s picture below that.

Then we create the cards array in the order of their magnitude by combining the values from the suits and values array.

In the data method,. we have the reactive properties in the object we return.

score has the score.

cards has a copy of the cards array shuffled with sort .

guess has the guess which can be 'lower' or 'higher' .

In the draw method, we take the card with pop .

And then we push that into drawnCards .

Then we have get the index of each card from the original card array, which is sorted in the order of their magnitude.

Then finally, we have an if block that compares the index of the last and currently drawn card and the guess.

If they match the condition, then score is increment by 1.

Conclusion

We can create a high-low card game easily with Vue 3 and JavaScript.