JavaScript MP3 player

Could someone kindly point out where I went wrong? I am attempting to create an MP3 player using CSS, HTML, and JavaScript. Currently, the script only functions to start or stop the audio file. However, I keep encountering an error message: TypeError: document.getElementById(...) is null; Unfortunately, I'm unsure why this is happening. Thank you for any assistance!

Script:

<html>
<head>
    <meta charset="utf-8" />
    <title>Audio Player</title>
</head>
<body>

    <script type="text/javascript">

    var audio = document.getElementById('#listen');
    document.getElementById('#control').addEventListener("click", function() {
        if(audio.paused) {
            audio.play();
        } else {
            audio.pause();
        }
    })


    </script>

    <audio id="listen" src="song.mp3">
        ERROR
    </audio>

    <button id="control">Control</button>

</body>
</html>

Answer №1

As mentioned in this stackoverflow post, a recommended practice is to place your scripts at the bottom of the body tag to prevent timing issues. Here's a revised version of your code:

<html>
<head>
    <meta charset="utf-8" />
    <title>Video | Audio</title>
</head>
<body>



    <audio id="listen" src="song.mp3">
        ERROR
    </audio>

    <button id="control">control</button>

    <script type="text/javascript">

    var hear = document.getElementById('listen');
    document.getElementById('control').addEventListener("click", function() {
        if(hear.paused) {
            hear.play();
        } else {
            hear.pause();
        }
    })


    </script>

</body>
</html>

Prior to this adjustment, the issue was that web pages are parsed sequentially, meaning elements may not have been created when a script runs. This is why your button could not be found by the script. Remember to use getElementById without the hash symbol when retrieving elements.

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

Struggling to retrieve the dynamic select list information from HTML and pass it to PHP. Any suggestions or guidance would be greatly

<form method="POST" name="mailform" action="sendmail.php"> <fieldset> <?php require_once("mysql_connect.php"); $sql = mysql_query( " SELECT NAME FROM TABLE WHERE ID = ( SELECT ID FROM TABLE2 WHERE COLUMN = '$USERNAME') ORD ...

Utilize Moment.js in AngularJS for formatting dates

I have been attempting to use moment.js in Angularjs to format a date, but it seems like I am running into some issues. Here is the link to my code snippet on jsfiddle http://jsfiddle.net/sed6x5e8/ and below you can find the HTML and JS code that I am work ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

CSS: Apply unique padding to the last element without the use of additional classes

My challenge involves a div housing three images, each about 31% in width. The goal is to have padding between them, with the final image having no right padding so that collectively they match the width of a larger image above. Here's an example... ...

Locate a specific option that matches the value of the selected data-status and set it as "selected" using jQuery

Currently, I am facing an issue where I need to load 2 separate ajax responses into a select dropdown. The select dropdown will have a data-status attribute, and my goal is to loop through the options to find the one that matches the value of the select da ...

Issues with the background-image scroll feature not functioning as intended

Can anyone help me out with a CSS issue I'm having? I've set an image as my background on a webpage and I want it to scroll with the page. Even though I followed some online tutorials, it's still not working for me. It's been a while si ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

Managing email delivery and responses within Nextjs server functions using Nodemailer and React Email package

Currently, I'm working on a Next.js project that involves sending emails. The functionality works as expected, but I've encountered an issue when trying to verify if the email was successfully sent or not. Here's my current setup: await tran ...

Troubles with Installing CRA and NextJS via NPM (Issue: Failure to locate package "@babel/core" on npm registry)

Summary: Too Long; Didn't Read The commands below all fail with a similar error message... Couldn't find package "@babel/core" on the "npm" registry create-react-app test npm install --save next yarn add next Details of Running create-re ...

Angular Universal causes SASS imports to malfunction

Check out this sample app that you can download to see the issue in action: https://github.com/chrillewoodz/ng-boilerplate/tree/universal I am currently working on implementing angular universal, but I'm encountering an error with a SCSS import in o ...

Optimize my webpage for a specific location

While developing a game website, I am interested in learning how to enable only specific parts of my website to function while disabling the rest. How can this be achieved? ...

Mastering the Art of Incorporating jQuery, JavaScript and CSS References into Bootstrap with ASP.NET WebForms

Hey there, I'm currently working on a personal project as a beginner in Bootstrap. My main challenge for the past two days has been trying to integrate a dateTimePicker and number Incrementer using Bootstrap techniques. Despite my efforts in researchi ...

What is the best way to sort ISO DateTime objects that fall outside of a particular time frame?

I'm currently working on a project that involves a list of objects with properties for startTime and endTime, all in ISO format. Here's a snippet of the list: list = [ { startTime: '2022-06-26T10:00:00.000Z', endTime: '2022- ...

Failure encountered when attempting to load JSON data into datalist

I've been trying to incorporate inputs into a datalist in two different ways. However, I've encountered an issue with the first method not working properly. --> Check it out on bootlply var dataList = document.getElementById('json-datal ...

Facing an issue with Heroku deployment where a React/Express app is encountering a 'Failed to load resource' error in the console while requesting the chunk.js files

Upon deploying my React application on Heroku, I encountered errors in the console. Refused to apply style from 'https://radiant-tor-66940.herokuapp.com/index.css' because its MIME type ('text/html') is not a supported stylesheet MIME ...

Display my additional HTML content on the current page

Is it possible for my addon to open a predefined html page in the current window when it is started? And if so, how can this be achieved? Currently, I am able to open my addon page in a new window using the following command: bridge.boot = function() { ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

Is there a solution to resolving the type error that I am unable to identify?

I am attempting to implement a custom cursor feature in Vue 3, but unfortunately my code is not functioning as expected. Below you can find the code snippet I have been working on: <template> <div id="cursor" :style="cursorPoi ...

Tags that adhere to W3C compliance for struts

I'm facing an issue with a web page created using struts tag libraries. When attempting to validate the page on w3c.org, all the struts tags are showing up as undefined. For example, <html:button> appears as undefined. The DOCTYPE I used is: &l ...

Set the android camera resolution to a lower setting automatically when a user attempts to upload a file from their browser

In my current application, I have implemented a feature that allows users to upload files. When the user clicks on the input field, they are presented with options to either select a video from their gallery or open the camera to record a new video and u ...