Sari Broudy
Sari Broudy

Reputation: 1

Is there something wrong with my code in my .js file for the pause button?

This is my current code for a music player im building for my portfolio. I am having an issue getting the button to pause. the music does play so that is not an issueyour text

const music = document.querySelector('audio');
const prevBTN = document.getElementById('prev');
const playBTN = document.getElementById('play');
const nextBTN = document.getElementById('next');

// Check if Playing
let isPlaying = false;

// Play
function playSong() {
    let isPlaying = true;
    playBTN.classList.replace('fa-play', 'fa-pause');
    playBTN.setAttribute('title', 'Pause');
    music.play();
}

// Pause
function pauseSong() {
    let isPlaying = false;
    playBTN.classList.replace('fa-pause', 'fa-play');
    playBTN.setAttribute('title', 'Play');
    music.pause();
}

// Play or Pause Event Listener
playBTN.addEventListener('click', () => (isPlaying ? pauseSong() : playSong()));

I have tried changing the names of attributes

Upvotes: 0

Views: 32

Answers (1)

Samathingamajig
Samathingamajig

Reputation: 13283

In your functions, you say let isPlaying = .... This creates a new variable in the lexical scope of the function, not changing the global variable.

// Play
function playSong() {
    isPlaying = true;
    playBTN.classList.replace('fa-play', 'fa-pause');
    playBTN.setAttribute('title', 'Pause');
    music.play();
}

// Pause
function pauseSong() {
    isPlaying = false;
    playBTN.classList.replace('fa-pause', 'fa-play');
    playBTN.setAttribute('title', 'Play');
    music.pause();
}

remove the let and you'll be fine

Note that this doesn't account for when you get to the end of the song, where isPlaying will still be true.

Upvotes: 1

Related Questions