Implementing the Audio() Element with JavaScript

I've written the code below, but it's not working properly! When I click on the play button, nothing happens

HTML:

<button id="play"><img id="playicon" src="img/Polygon 1.svg"></button>

JS: I have a variable named 'song0' for sound, and it's supposed to play or pause in the 'playPauseEvent' function. However, it doesn't perform as expected. I found this method on the following site

var playpause, play1icon, song0;

function aslekar(){
    song0 = new Audio('audio/Meydoon.mp3');
    song0.loop = true;
    song0.play();

    document.getElementById("moon");
    play1icon = document.getElementById("playicon");
    playpause = document.getElementById("play");

    playpause.addEventListener("click", playPauseEvent);

    function playPauseEvent(){
        if(song0.paused){
            song0.play();
            play1icon.setAttribute("src", "img/Polygon 1.svg");
        }else{
            song0.pause();
            play1icon.setAttribute("src", "img/Group 1.svg");
        }
    }
}
window.addEventListener("load", aslekar);

I am very new to coding and would appreciate any help with this :)

Answer №1

Feel free to test this out by clicking on the Live Preview

var playpause, play1icon, song0;

function aslekar(){
song0 = new Audio('https://gamepedia.cursecdn.com/dota2_gamepedia/d/db/Vo_crystalmaiden_cm_kill_07.mp3');
song0.loop = true;
song0.play();

document.getElementById("moon");
play1icon = document.getElementById("playicon");
playpause = document.getElementById("play");

playpause.addEventListener("click", playPauseEvent);

function playPauseEvent(){
    if(song0.paused){
        song0.play();

        play1icon.setAttribute("src", "https://image.flaticon.com/icons/svg/64/64485.svg");
    }else{
        song0.pause();

        play1icon.setAttribute("src", "https://image.flaticon.com/icons/svg/27/27223.svg");
    }
}
}
   window.addEventListener("load", aslekar);

You can also view the corresponding html below

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button id="play" onclick="playPauseEvent()"><img id="playicon" src="https://image.flaticon.com/icons/svg/27/27223.svg" width="30" height="30"></button>
</body>
</html>

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

Link commitments and ornament an entity

I'm struggling to grasp the concept of promises, specifically in chaining them and enhancing an object with data fetched from various endpoints. For instance: In my node-express application, I have the following code //controller.js export const ge ...

A table featuring an HTML select element that allows users to choose from preset options or manually enter

My goal is to incorporate a select box where users can either choose from a set list of options or input their own custom value. The select element is nested within a table. Unfortunately, using datalist is not a viable solution for me in this case. I have ...

The JSON array provides the ideal syntax for looping purposes

I am working with JSON data and trying to check if a hovered element matches the names 'sports' or 'technology'. If there is a match, I want to retrieve the corresponding 'text' and 'image' values. However, I am only ...

Can select2 and a jQuery Virtual Keyboard work together seamlessly?

Is there a method to implement a jQuery virtual keyboard for inputting into a Select2 select box? The issue is that the dropdown in the Select2 component closes automatically when clicked away from, preventing the use of a web-based virtual keyboard. If ...

When running npx webpack, an error occurred stating, "Property 'minify' cannot be read from undefined."

I've been following the introductory tutorial on webpack from this particular link: https://webpack.js.org/guides/getting-started/ However, when I attempt to execute npx webpack, it encounters an error as shown below: ERROR in main.js from Terser Ty ...

Export data table from HTML to Excel successfully implemented with C#

I am currently working on an Umbraco website and developing a custom plugin for the backend that allows users to export an Excel worksheet from an HTML table. In order to achieve this functionality, I am utilizing AngularJS along with a C# controller. Belo ...

Passing a JSON object between pages in Next.js using props during programmatic navigation

In my Next.js project, I have two pages. On the first page, the user fills out a form to create a post. The information is stored in a large JSON object, which needs to be passed to the second page for the user to preview the post before finalizing it. Wi ...

What could possibly prevent Jasmine Spyon from being named?

I am currently facing an issue with a failing test even though I have included the necessary calls. One specific area where I am encountering this problem is with the PrimeNG Message Service that I am spying on. Below, you can find the code snippet that I ...

Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site. return this.getFields() .reduce((mappings, field) =& ...

Explore various locations and conceal different divs by clicking

Can someone help me figure out how to hide the placeholders when the focus changes in a form? Here is the code snippet that illustrates my problem. Your assistance is greatly appreciated, João var inputs = Array.prototype.slice.call(document.querySele ...

What methods with JavaScript, Ajax, or jQuery can I apply to populate the student details?

For completing the StudentID section, please fill out the form data.cfm with the first name, last name, and Middle Name. <script language="Javascript"> $(function() { $( '#effective_date' ).datepicker(); jQuery.validator.addMetho ...

What steps can be taken to ensure that the content in column two does not impact the positioning of content in column one?

Is there a way for the input text container to remain in its original position within the layout even after submitting text? Usually, when the data displayed container's height increases, it pushes the input text container down. Despite trying absolu ...

The conversion of XML to HTML using setQuery(QString) in QXmlQuery is unsuccessful

Whenever I use the method setQuery(QUrl(file.xsl)), it functions properly. However, if I first load the file into a QString and then invoke setQuery(theString), the subsequent evaluateTo() operation fails (resulting in a boolean exception and empty result) ...

ASP.NET can have issues with the functionality of jQuery AJAX

I'm currently working on an asp.net webform project and I'm looking to implement jQuery ajax functionality. Below is the code snippet I have so far: <asp:Button ID="btn_comment" runat="server" CssClass="contact_btn pull-right" Text="send" OnC ...

CSS - What's the source of this mysterious whitespace?

I'm currently making adjustments to a Wordpress website that is designed to be responsive. The site uses media queries to adapt its display based on the user's screen size, and everything looks great except for when the screen width is at its sma ...

The art of combining CSS3 gradients with background images

I've created a function that changes the parent element's background gradient when a checkbox's status is toggled. Check out the Lorem link to see it in action! Click here to view. However, I've encountered an issue with applying this ...

Searching for a particular Prettier setting

Seeking a Nicer alternative. I am exploring if there is a way to format code like this without moving the first attribute to a new line: <div class="test-class" [test-binding]="true" (test-binging)="test()" ...

What could be the reason for the d-flex class in bootstraps preventing my div from expanding to 100% width?

I have a div where I need to display two elements next to each other: a search input field and the corresponding submit button. My attempt so far was to achieve this using the following code: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn. ...

span element causing border-spacing problem

Is there a way to adjust the spacing between these borders? I've tried using border-spacing but it doesn't seem to be working. {{#each spacing}} <span class='space'> {{business}} ({{Count}}) </span> {{/each}} CSS .spac ...

Hovering over one element in Jquery triggers actions on multiple elements simultaneously

I'm working on a project where I have multiple cards, and I've implemented a hover effect using jQuery to make the images inside the cards bigger. However, I'm facing an issue where hovering over one card triggers the effect on all the other ...