Is there a way to stop music when I click?

After implementing the code snippet I discovered online, my website now plays audio when a specific button is clicked. However, I am interested in finding out how to modify the code so that the audio can be paused or stopped when the same button is clicked again. Any suggestions on how this can be achieved with similar code?

const rollSound = new Audio("./mp3/SoItGoes.mp3");
$('#Triangle').click(e => rollSound.play());

Answer ā„–1

To indicate the state of the player, you can assign a specific class to the button (class = "active" if it's active, no class if paused), and then assess this class during a button click event:

HTML:

<button id="Circle">Play/Stop</button>

JavaScript:

$('#Circle').click(function(e) {
    if ($(this).hasClass('active')) {
        stopSound();
        $(this).removeClass('active');
    } else {
        playSound();
        $(this).addClass('active');
    }
});

Answer ā„–2

To incorporate an if statement within your event handler for checking the button text value, you can implement the following approach:

HTML:

<button id="Triangle">Start</button>

JS:

const playSound = new Audio("./mp3/SoItGoes.mp3");
$('#Triangle').click((e) => {
  if($('#Triangle').text() === 'Start') {
      playSound.play();
      $('#Triangle').text('Stop')
  }
  else {
    playSound.pause();
    $('#Triangle').text('Start')
  }
});

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

The functionality of Breeze.js for saving changes fails unless the designated controller method is explicitly named as `SaveChanges()`

Hello, I am a beginner in BreezeJs I have a post method on my Controller // POST api/company/post [Authorize(Roles = "Admin")] [AcceptVerbs("POST")] [HttpPost] public object **SaveChanges**(JObject companyRequest) ...

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates ā€“ a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

Linking a background image in the body to a specific state in next.js

My aim is to create a pomodoro timer using Next.js and I'm trying to link the body's background image to a state. However, my code isn't functioning properly. This is the code I used to update the body style: import { VscDebugRestart } from ...

Customize jQuery Slider

I recently implemented a slider using code from an online tutorial found here: http://jsfiddle.net/RXpjM/ While I have a good understanding of how the code functions, I am facing a challenge with the "going back to the beginning" option. Currently, the sl ...

Javascript onclick events failing to toggle video play/pause functionality

In my website, I have background music and a background video (webm format) embedded. I am facing an issue with making play/pause buttons in the form of png images work for both the video and the music. The background music is added using the embed tag wi ...

Display a text decoration effect when hovering over a division

Is there a way to change the color of a link when hovering over the entire div it's in, rather than just the link itself? Can this effect be achieved using only HTML & CSS? For instance, if I had (jsfidde), how could I make the link turn blue when ho ...

Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example: $("head").append('<script type="application/javascript" src="core/js/main.js"></script>'); I'm asynchronously pulli ...

Interacting with dynamically loaded HTML content within a div is restricted

On my main HTML page, I have implemented a functionality that allows loading other HTML pages into a specific div using jQuery. The code snippet looks like this: $('.controlPanelTab').click(function() { $(this).addClass('active').s ...

Display the precise outcome for each division following a successful AJAX callback

Iā€™m facing a challenge in getting individual results for each item after a successful AJAX callback. Currently, I am able to retrieve results, but when there are multiple items, all displayed results are being added to each div instead of just the corres ...

The page is failing to redirect to the view following the successful invocation of a Jquery Ajay method

Utilizing the JQuery ajax method to invoke a controller from a view has been successful in calling the controller's action method, retrieving data from the database, and displaying it in the corresponding view. However, despite this success, the view ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Guide for running an await function consecutively with JavaScript and React

I have the following code snippet: const somePromises = values.map(({variable, value}) => this.post('/api/values/', { variable, value, item: itemId, }) ); await Promise.all(somePromises); if (somecondition) { ...

Is it possible to utilize Ionic for making an Ajax JQuery POST request?

As I try to implement NTLM authentication from my Ionic app, I have successfully tested the request using Postman. While Postman works with NTLM Authentication option, it does not offer any code for Angular (specifically for Ionic). In my research, I disc ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

Controlling factory JSON data with $http calls using two separate controllers

I'm attempting to retrieve a JSON response from a factory, save it as a variable, and make it accessible from two different controllers. Below is the code I am utilizing: storyFactory.js var story = angular.module('story.services', []); ...

Require the implementation of seamless scrolling when clicking on an anchor tag with a specific ID, as opposed to the abrupt jumping to the corresponding

<div id="slider"> <div id="pro1"></div> <div id="pro2"></div> <div id="pro3"></div> </div> <div id="thumb"> <a href="#pro1"> <img id="tpro1" src="projects/tpro5.jpg" style="hei ...

Is it possible to insert items into Vue component data? I'm interested in creating a table following JavaScript filtering and manipulation

I'm working on a website that will have multiple pages, each containing tables. To streamline this process, I wanted to create a table component. However, I haven't added any data to the tables yet because I need to manipulate it using JavaScript ...

The issue of jquery noConflict not functioning properly in a php include() statement is

Having trouble with jquery.noConflict not working when loading from an external file using php includes? Also noticing that some scripts may not be fully loading as well. Mainfile.php <script type="text/javascript" src="js.jquery/jquery.1.8.2.min.js"& ...

Determine the sum of all the values entered into the text fields

On my ASP.Net page, there is a screen where users can select between 1 and 5 text boxes to input an amount. Depending on certain criteria, a specific number of these edit boxes are displayed - no hiding involved. So if I choose to display 3 boxes, only 3 w ...

Consolidating Arrays in MongoDB: A Handy Function

I have a substantial dataset containing documents that sometimes reference each other and sometimes do not. Before I can perform mapreduce operations based on these cross-references, I need to ensure that the array of cross-references is consistent for eve ...