Having trouble getting my JS/CSS code to work for a single image music play/pause button. Any suggestions on how to fix it?

I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to function properly. I've searched for solutions on CodePen, but haven't had any luck. I'm really hoping someone can offer some assistance. At one point, I did manage to get it working, but the pause function was not working correctly, so I had to rewrite the code.

Here is the HTML snippet related to the music button:

<ul>
  <li class="nav-item nohover">
    <audio id="music-button">
      <source src="Zara%20Larsson%20Lush%20Life%20Lyrics.mp3" preload="auto" type="audio/mpeg" />
    </audio>
    <div id="music-button-container">
      <div id="play-pause" class="play"></div>
    </div>
    <!--<a onclick="musicPlay()"><img src="music2.png" width="65px"></a>-->
  </li>
</ul>

Here is the CSS code related to styling the music button:

#music-button-container,
#play-pause {
  cursor: pointer;
  height: 50px;
  width: 70px;
  padding: 12px 18px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 50px;
}

.play {
  background-image: url(./music2.png);
}

.pause {
  background-image: url(./equalizer.png) !important;
}

Lastly, here is the JavaScript code that I believe is causing the issue:

var music = document.getElementById('music-button');
     var controlButton = document.getElementById('play-pause');

     function musicPlay() {
        if (music.paused) {
        music.play();
        controlButton.className = "pause";
         } else {
           music.pause();
           controlButton.className = "play";
         }
       }
     
     controlButton.addEventListener("click", musicPlay);
     music.addEventListener("ended", function () {
     controlButton.className = "play";
     });

     /* This is what I have tried as well*/

     document.querySelector(".play-pause").addEventListener("click",
     function() {
     if (music.paused) {
        music.play();
      } else {
        music.pause();
      }
     });

     function musicPlay() {
       var music = document.getElementsById("music-button");
       return music.paused ? music.play() : music.pause();
      }

     var isPlaying = false;

     function musicPlay() {
      return music.paused ? music.play() : music.pause();
     }
       music.onplaying = function() {
       isPlaying = true;
     };
     music.onpause = function () {
       isPlaying = false;
     }

Answer №1

Hey there! Just a heads up, using only one condition in an if statement may not work as expected. Picture this scenario: the audio hasn't even started playing yet, but that doesn't necessarily mean it's paused.

// You can use this code snippet
const play = document.querySelector(".play-pause")

// Pay attention to the arrow function syntax below
play.addEventListener("click",()=>{
  if(music.paused || music.currentTime >=0){
    music.play()
  }
  else{
    music.pause()
  }
})

Give this a try, it should work smoothly. If you need further assistance with your music website,

Feel free to check out my site at

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

Breaking apart paragraphs in a text using JavaScript

Hello, I am working on a code that is supposed to extract paragraphs from text entered into a textarea and create an array containing each paragraph. For example, it should turn text like this: Hello, that's the first paragraph Hello, that's th ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

Should you choose a pre-built CSS framework or create your own from scratch?

Have you come across a framework that meets your project needs with just a few tweaks, or have you forged your own path along the way? What advice do you have for someone facing this decision and focusing on priorities like: Implementing a CSS reset Refi ...

Retrieve the URL of the previously visited webpage using Javascript

Is there a way to retrieve the URL of the last visited page using JavaScript? I want to be able to track which product the user viewed most recently. I have attempted the following code: var x = document.referrer; document.getElementById("demo").innerHTML ...

The <div> element is not compatible with the <canvas> element for use

I'm having trouble inserting a <canvas> animation within a <div> element. The current code displays the animation across the entire page, but I would like to contain it within a single section, like this: <div><canvas> </can ...

Show and hide the div by clicking a button

Looking at the image below, my goal is to display the div under the reply button. (The div consists of a text box and send button) https://i.stack.imgur.com/jnaV4.png The code I have currently functions correctly. However, when clicking any reply button ...

Incorporate a platform-specific button in a user interface with React Native

I need to display a button that is only shown on iOS, not on android. I have tried using the following style, but it doesn't seem to be working. ...Platform.select({ android: { display:'none', }, The code for my button is: <Bu ...

Is it necessary to execute 26 individual mysql queries in order to group items alphabetically in a directory listing page?

I am looking to create a directory listing page for my website that displays all of my articles grouped by the first letter of their titles. Do I have to execute 26 MySQL queries like: mysql query like "SELECT * FROM articles Where title like 'a%&ap ...

Effortless glide while dragging sliders with JavaScript

In the code below, an Object is looped through to display the object key in HTML as a sliding bar. jQuery(function($) { $('#threshold').change(updateThreshold); function updateThreshold () { var thresholdIndex = parseInt($(&apos ...

Turn off link preview feature on Android messages

As a developer, I am looking for a way to disable or hide link previews on Android devices when someone receives a text message with a link to our website. I still want the URL address to be visible, but I prefer to keep the link previews on IOS devices. I ...

Variances in the order of HTML elements within an article's layout

Check out this example of HTML and CSS <!DOCTYPE html> <html> <head> <title>Floats Example</title> <style type="text/css"> .left { float:left; width:100px; } .righ ...

Looking to notify the second set of JSON data arrays?

Today, I encountered an issue while working with two arrays of JSON data. Upon trying to alert the second JSON data in AJAX, I found that it was showing as "undefined". How can I successfully alert the value of the second JSON data? The relevant portion o ...

Issues with retrieving $_POST values from a select form in PHP

When the button is clicked, I am sending a AJAX request to my PHP page using POST method with the selected data from a SELECT element. However, I am facing an issue where my PHP IF statements are not evaluating as true. It always defaults to the ELSE condi ...

Is there a way to seamlessly roll the camera using a button in ThreeJS alongside TrackballControls without causing any conflicts?

When working with ThreeJS, I encountered an issue with rotating the camera using a button. Here is the code snippet I used: camera = new THREE.PerspectiveCamera(...) function roll(angle) { const quaternion = new THREE.Quaternion(); const lookat = ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

Using the `scrollIntoView()` method to continuously scroll through elements in Puppeteer

My goal is to extract a list of posts while the page is continuously loading. I am using scrollIntoView() for each element within a loop. Currently, my code looks like this temporarily. When the page loads, the result bounces out without any errors. for (l ...

Populate a dropdown list with array elements using Javascript in ReactJS

I am encountering an issue while trying to populate a dropdown with data from the 'options' array. The error message states that it cannot read property appendChild of null. Using 'document.getElementByClassName' instead of document.ge ...

The navigation dropdown menu in Bootstrap 4 spills over the edges of the window

In the code snippet provided above, an example of a navbar with a dropdown menu is given. One issue that arises is when the dropdown menu is clicked and it overflows to the right, causing a horizontal scroll bar to appear on the window. The question at ha ...

What would be the JavaScript counterpart to python's .text function?

When using Element.text, you can retrieve the text content of an element. Recently, in a separate discussion on SO, there was a Python script discussed that scraped data from the followers modal of an Instagram account. The script is designed to capture t ...

Using JavaScript to dynamically calculate the sum of selected column values in Angular Datatables

I have a table set up where, if a checkbox is checked, the amounts are automatically summed and displayed at the top. However, I am encountering issues with the code below as it is not providing the exact sum values. Can anyone suggest a solution to this p ...