the eventListener is not functioning as expected when used with the 'else' keyword

Everything seems to be working fine until I click on playsong1. The code executes as expected for the first click, but when clicked again, instead of progressing to the conditions after the } else { statement, it re-triggers the same conditions (replaying the audio track from 00:00). I'm trying to make it function more like a 'play/pause' button. What am I missing here?

playsong1.addEventListener("click", function () {
   song1.classList.add("song-boxes-active");  
   song4.classList.remove("song-boxes-active");
   song2.classList.remove("song-boxes-active"); 
   song5.classList.remove("song-boxes-active");
   song3.classList.remove("song-boxes-active"); 
   song6.classList.remove("song-boxes-active");
   playsong1.innerHTML = "<i class='fa fa-pause-circle-o'></i>"; 
   playsong4.innerHTML = "<i class='fa fa-play-circle-o'></i>";
   playsong2.innerHTML = "<i class='fa fa-play-circle-o'></i>";
   playsong5.innerHTML = "<i class='fa fa-play-circle-o'></i>";
   playsong3.innerHTML = "<i class='fa fa-play-circle-o'></i>";
   playsong6.innerHTML = "<i class='fa fa-play-circle-o'></i>";
   
if (playlist_index !== 0) {
    audio.src = dir + playlist[0] + ext; 
    playlist_status.innerHTML = playlist[0];
    playlist_index = 0;
    playPause();
    console.log('cond1');
} else if ((!audio.paused) && playlist_index === 0) {
    playPause();
    playsong1.innerHTML = "<i class='fa fa-play-circle-o'></i>";
    playbtn.innerHTML = "<i class='fa fa-play'></i>";
    console.log('cond2');
} else if((audio.paused) && playlist_index === 0) {
    playsong1.innerHTML = "<i class='fa fa-pause-circle-o'></i>"; 
    playPause();
    console.log('cond3');
}
});

//original code posted
//playsong1.addEventListener("click", function () {
// audio.src = dir + playlist[0] + ext; playlist_status.innerHTML = //playlist[0];
 //if (audio.paused) {
 //  song1.classList.add("song-boxes-active");
  // song2.classList.remove("song-boxes-active");
 //  song3.classList.remove("song-boxes-active");
  // playsong1.innerHTML = "<i class = 'fa fa-pause-circle-o'></i>";
  // audio.play();
  //  } else {
  //  audio.pause();
 //   playsong1.innerHTML = "<i class = 'fa fa-play-circle-o'></i>";
// playbtn.innerHTML = "<i class = 'fa fa-play'></i>";
// document.getElementById("glow").classList.add("disable-animation");
// }
//});

Answer №1

By initializing the src of the <audio> element within the click event, you are triggering an automatic pause for the audio.

const audio = document.querySelector("audio");
const button = document.querySelector("button");

button.onclick = async (evt) => {
  await audio.play();
  console.log( "initial", audio.paused ); // false
  audio.src = audio.src; // even if it remains the same value
  console.log( "final", audio.paused ); // true
};
<button>click to play</button>
<audio controls src="https://example.com/audio-sample.mp3">

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

Out of reach: Menu div slides up on click outside

<a class="btn">Click ME </a> <div class="content"> Content </div> $('.btn').click(function(){ $('.content').slideToggle(); }); Check out the example here Everything is working properly, but I have a q ...

Exploring the Depths of React by Cycling Through Arrays in Tabular Format

One issue I'm facing is that I have an array named paymentMethods which I'd like to iterate through in tabs. However, I seem to be struggling with the iteration part. To take a closer look at my code, please visit my codesandbox HERE <div& ...

Combining the `vuex-typex` npm package's `dist/index.js` for optimal performance with Jest testing framework

I initially raised this question as an open issue on GitHub. My experience with Vue.js, Vuex, TypeScript, and vuex-typex has led me to encounter syntax errors during Jest testing. I am relatively new to working with Vue.js, TypeScript, and Jest. It is wo ...

The issue of a blank first page occurring when attempting to print the contents of an

I am encountering an issue with printing a webpage that contains three images. When printing directly from Internet Explorer, it correctly prints three pages, one for each image. However, when loading the same page within an iframe and printing the iframe ...

How to Make Bootstrap 3 Collapse Panels Stand Out with an Active Class

First of all, here is the fiddle link: http://jsfiddle.net/krish7878/h38jn324 I have a simple question. When a panel is clicked and it expands to show its contents, a class 'active' should be added to 'panel-heading'. I came across a ...

How to effectively merge DefaultTheme with styled-components in TypeScript?

I am facing an issue with integrating a module developed using styled-components that exports a theme. I want to merge this exported theme with the theme of my application. In my attempt in theme.ts, I have done the following: import { theme as idCheckThe ...

What's the most efficient method for managing the spacing between block elements?

Is there an optimized method for adjusting the spacing between specific block elements? I have multiple instances of this issue. <div id="head1" class="global-box"> <p>My Header Name</p> <select id="Select1"> <o ...

Ending a timed function in AngularJS 1

As part of my Angular JS 1 learning journey, I am working on a small test involving text areas that display text using Angular functions when a user enters and exits them. The enter function has a 3-second delay, while the exit function waits for 5 seconds ...

"Revamping Your Design: The Power of Angular 4

I am working with two different layouts in my project: <div *ngIf="!loginPanel" class="login1"> <a (click)="showLoginPanel()">Login</a> </div> <div *ngIf="loginPanel" class="login2"> <input type="text" placeholder="user ...

Looking to utilize vue.js to alter the color of the <li> element when a select option is chosen

I'm a beginner in vue.js and I'm attempting to change the background color by using the select option. Despite trying the cueCardsColor method, nothing seems to be happening. <ul> <li :class="+ cueCardColor"> <sele ...

Verify whether the element in the DOM is a checkbox

What is the method to determine whether a specific DOM element is a checkbox? Situation: In a collection of dynamically assigned textboxes and checkboxes, I am unable to differentiate between them based on their type. ...

Creating a Conditional "Retrieve Script File" Function in JavaScript Without Dependencies

At the company where I work, we have numerous clients with their own websites that are connected to our system through a linking mechanism. Essentially, these clients have a link on their website that directs users to our site upon clicking. I am working ...

Utilize three.js to set the camera's position and rotation

In my current setup, I have a particular object in view using a PerspectiveCamera. By utilizing OrbitControls, I can navigate around the object, rotate it, pan it, and more. My goal is to reposition the object to a specific location at a specific angle an ...

Encountering a 401 error message with a 'truncated server' response while using Google Apps Script

I'm currently working on a code snippet that looks like this. function method3() { var spreadsheetID = '1BGi80ZBoChrMXGOyCbu2pn0ptIL6uve2ib62gV-db_o'; var sheetName = 'Form Responses 1'; var queryColumnLetterStart = ...

Is it advisable to clear the bootstrap tooltips array in order to conserve browser memory once I have finished rendering new tooltips?

My apologies if this question has been asked before, but I searched online first and couldn't find a helpful answer. Beautiful Views Recently, I was working on a project where I needed to display search results, each accompanied by a button that trig ...

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

Having troubles with angular due to doodle throwing errors?

https://codepen.io/tuckermassad/pen/rPYNLq I took the CSS doodle code from the above link and incorporated it into my angular component: <section class="main"> <css-doodle grid="5"> :doodle { @grid: 10 / 100%; } ...

Ways to disable HTML loading prior to CSS loading

After downloading a site template, I observed that the HTML is loaded first before the CSS. Is there a way to disable this? I am looking to create a preloader for the website. ...

The link in the drop down select is not functioning in IE8/9. When trying to open the drop down select link, an

Could use some help with IE8 and 9 compatibility, can't seem to find a solution. This code works smoothly on Chrome, FF, and Safari. There are two dropdown menus, each with two links. Every dropdown menu has its own "Buy Now" button. Upon selecting ...

What is causing compatibility issues between Firefox and the provided CSS code?

I am experiencing an issue with the page layout in FireFox. The widths are not displaying correctly and the upload button does not work. However, I have no problems when using IE or Chrome. I have reviewed the code but cannot find any errors. Here is the ...