I find myself having to click twice in order to play a song

I am creating a music player using basic html, css, and javascript. However, I have noticed that I have to click twice in order to play a song.

import data from './data.js';

const music = document.querySelector('audio');
const forward = document.getElementById('forward');
const back = document.getElementById('backward');
const play_push = document.getElementById('play_pause');

console.log(data[0]);
let isMusicPlaying=false;

const play =()=>{
    music.play();
    isMusicPlaying=false;
}

const pause =()=>{
    music.pause();
    isMusicPlaying=true;
}
// play pause function

play_push.addEventListener("click", (e)=>{
   if(isMusicPlaying){
    play();
   }
   else {
    pause();
   }
     
})

// functions for moving forward and backward
let  counter = 0;
forward.addEventListener("click", ()=>{
    counter++;
    music.src=data[counter].song;
    console.log(data[counter]);
})

backward.addEventListener("click",()=>{
    counter--;
    music.src=data[counter].song;
    console.log(data[counter]);
})

Below is my HTML code:

<div class="container">
        <div class="musicCard">
            <div class="titles">
                <h2>name</h2>
                <h3>artist</h3>
            </div>
            <div class="cardImage">
                <img src="" alt="">
            </div>
            <audio src="./Data/songs/Akhiyan.mp3"></audio>
            <div class="controller">
                <div class="fa-solid fa-backward" id="backward"></div>
                <div class="fa-solid fa-play" id="play_pause"></div>
                <div class="fa-solid fa-forward" id="forward"></div>
            </div>
        </div>
    </div>

I have a folder containing songs and a 'data.js' file with an object array that includes the paths and names of the songs. Despite checking everything, I can't seem to figure out what's wrong with my code.

Answer №1

Consider updating your event listener callback function like so:

play_push.addEventListener("click", (e)=>{
   if(!isMusicPlaying){
    play();
   }
   else {
    pause();
   }
     
});

The 'if' condition will execute when the specified condition is true. In this scenario, 'isMusicPlaying' is initially set to false. To fix this, I modified 'isMusicPlaying' to '!isMusicPlaying', indicating "if music is NOT playing, then play music."

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving the positions of a mesh as it looks towards an object in three.js

My scenario involves having a scene, multiple meshes, and a target object. After setting up the scene, I use the code snippet below to make a mesh (referred to as mesh) face the target object: mesh.lookAt(object) This action successfully aligns the me ...

using configureStore instead of createStore

After updating my packages, I received a notification from VScode indicating that the createStore function was deprecated. This prompted me to go ahead and replace it with the recommended alternative. In my store file, I left the original line as a commen ...

Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller. Service: class userService { constructor ($http, ConfigService, authService) { th ...

Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table. Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I n ...

Make sure the a-tag is set to be displayed as a block element, but keep

I'm trying to style an anchor tag as a block element for specific design purposes - setting the width, height, and padding. However, I also need this block element to be hidden initially, so I've used CSS to set its display value to none. The is ...

Repeatedly encountering identical values in delayed for loop

I can't figure out why my delayed for loop is consistently giving me a "-1" as the result. for (var i = 5; i > 0; i--) { setTimeout(function() { console.log(i) }, i * 1000) } (I adjusted my variable to be 5) ...

Execute a function only once when using it in conjunction with ng-repeat in AngularJS

I need a way to ensure that a specific function is only called once when used in conjunction with ng-if and ng-repeat. <td ng-if="!vm.monthView && vm.yearView=='contract-year'" nginit="vm.ContractYearBaselines()" class="baseline-data ...

"Navigate with Ease: Introducing the Twitter Bootstrap Scroll

Having trouble with the twitter bootstrap scroll spy feature as the navigation doesn't update until midway through scrolling and skips item 4 to reach the last item. Check out this example: http://jsfiddle.net/eoboite/kjvAa/38/ What am I doing wrong? ...

How to Retrieve CLOB Data Using MobileFirst 7.1 JavaScript Adapter?

function retrieveUserDetails(userId) { var userData = {}; var queryResult = WL.Server.invokeSQLStatement({ preparedStatement: getUserSQL, parameters: [userId] }); userData = { name: queryResult.resultSet[0]['N ...

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

The issue of jQuery not loading within Ajax content has been resolved

Appreciate the assistance provided. I am facing an issue where my jQuery code does not load within ajax content. Below is the code snippet from index.html : <script language="javascript" type="text/javascript"> $(function() { $("#gps").load("find. ...

Ways to reset the selected option when the user chooses a different option using either Jquery or Vanilla JavaScript

I am currently working on a functionality to clear the select option when a different brand is selected. The issue I am facing is that when I choose another brand, the models from the previous selection are not cleared out. For example, if I select BMW, I ...

Creating a query string in MongoDB using [Object] as a field

Currently, I am in the process of constructing a string within Meteor to delve deeper into my MongoDB data. The structure of my data can be seen here: Data In my JavaScript code for Meteor projects, I have formulated the string as shown below: const co ...

Having trouble calculating the sum of two numbers in JavaScript?

I recently encountered an issue in my code where I had a number array and was trying to display the sum in a text field. However, whenever I added a new number to the array and tried to calculate the sum again, it would concatenate instead of adding up pro ...

Error: Unable to locate module: Could not find '@/styles/globals.scss'

I'm encountering an error message with my import statement for the SCSS file in my _app.tsx. Can someone help me find a solution? I'm working with Next.js and have already exhausted almost every resource available online to fix this issue. ...

Issue with updating a select tag using ajax in Internet Explorer

I encountered an issue with the inner HTML function while updating option tags in a select tag. When I select a country in the first select tag, the AJAX code should update the cities in the other select tag. The code works fine in all major browsers excep ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

Navigating a FormData object in javascript on a .NET WebAPI version 5.2.2

I am currently working on integrating webcam video recording upload using the example provided in this RecordRTC GitHub repo. However, I have encountered a compiling error when trying to use "Request.Files" as indicated in the screenshot below. The error ...

Highcharts: Limiting the yAxis values to a maximum of two decimal places

Here is the code for my graph, which retrieves data from a PHP page and adds some series: $('#grafico_1').highcharts({ chart: { type: 'line', zoomType: 'xy', animation : false, events: { selection: functi ...

Resetting radio buttons and select fields upon dynamically adding a new input field in ReactJS

I'm currently working on creating a stack of input fields, and I want to be able to dynamically add a new input field to the page. My approach involves storing default fields in an array state and using setArr() along with the spread operator to add a ...