Modifying icons with JavaScript

When I click on the play icon, it changes to the pause icon. However, I am only able to change the first icon from play to pause in my JavaScript code. How can I apply this functionality to all the audio elements on the page?

let playIcon = "https://image.flaticon.com/icons/svg/149/149668.svg";
let pauseIcon = "https://image.flaticon.com/icons/svg/149/149670.svg";

function togglePlay(video) {
  var audio = document.getElementsByTagName("audio")[0];
  if (!audio)
    return;
  audio.paused ? audio.play() : audio.pause();
  document.getElementById("button").src = audio.paused ? playIcon : pauseIcon;
}
#button {
  width: 50px;
  display: block;
}
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149668.svg" id="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>

Answer №1

Instead of relying on the ID to retrieve the button, consider accessing it in relation to the element triggering the function. You can use the following function.

function togglePlay(element) {
  var audio = element.querySelector('audio');
  if(!audio) return;

  audio.paused ? audio.play() : audio.pause();
  element.querySelector('img').src = audio.paused ? playIcon : pauseIcon;
}

Answer №2

Check out this clever solution:

let playIcon = "https://image.flaticon.com/icons/svg/149/149668.svg";
let pauseIcon = "https://image.flaticon.com/icons/svg/149/149670.svg";

function togglePlay(video) {
  var audio = video.querySelectorAll("audio")[0];
  if (!audio)
    return;
  audio.paused ? audio.play() : audio.pause();
  video.querySelectorAll(".button")[0].src = audio.paused ? playIcon : pauseIcon;
}
.button {
  width: 50px;
  display: block;
}
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149668.svg" class="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149670.svg" class="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149668.svg" class="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>

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

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

What is the best way to display the weather information for specific coordinates in ReactJS?

I've been working on a code that retrieves farm details based on longitude and latitude. My goal now is to fetch the weather information for that specific farm using openweathermap However, each time I attempt to do so, an error message {cod: '4 ...

Ensure that my program is halted until the xmlhttprequest has completed

It seems like I've overcomplicated this problem for myself. In my page, I have 2 XMLHTTPRequests - the first request retrieves data from an API and fills my elements with this data. However, one of the fields in my elements requires a second request t ...

Jquery submenu accordion toggles open and closed with each click

My website has a hamburger menu with an accordion-style submenu implemented using jQuery for devices 1084px and smaller. For larger devices, the menu utilizes a hover-style submenu on desktop. However, I encountered issues when trying to use both the hove ...

Is there a way to define a specific browser for executing GWT tests?

In my GWT project, I am utilizing the HTML5 canvas feature. During testing, I rely on GWTTestCase to ensure application functionality. Some functions are only supported in Firefox starting from gecko 1.9. However, while testing with Firefox 3.0.1, err ...

What is the best way to assign an active class to a specific footer ID on an HTML page using AngularJS?

I tried using the activeLink directive to apply an active class to a specific id on the page, but it didn't work as expected. .directive('activeLink', ['$location', function (location) { return { restrict: 'A', ...

Initiating PHP outcomes with the integration of JQUERY and Bootstrap

Currently, I am working on a Twitter search functionality that allows me to search for any content on Twitter. While the feature is functional, I am facing some challenges with displaying the results in the desired format. Ideally, I would like the results ...

Looking for assistance with aligning an image in a <td> cell that doubles as a link?

How can I center a play icon in the middle of a td cell and make the entire content clickable as a link, including the background image? I've tried various methods but can't seem to get it right without breaking the alignment. Any suggestions wou ...

I am facing issues with jQuery's live and livequery functions when trying to use them with a form that is being loaded dynamically through

Previously, I inquired about a related issue regarding attaching behavior to an element with jQuery after insertion. However, I have not yet found a solution. For clarity's sake, I am posing a new question with a different scenario. Below is the code ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Enlarge an element to the extent of filling the list item

I am facing a challenge in expanding the a elements within this jsfiddle to fully occupy the li element. The use of display:block does not seem to be effective since I am utilizing a table for spacing. What steps can I take to achieve this while ensuring ...

Challenge with the desktop sidebar in a responsive design

Disclaimer: Seeking input on how to address this issue kindly suggest another title for editing Situation I have a responsive design layout for mobile and desktop with different blocks: Mobile | block1 | | block2 | | clientInfos | | eq ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

Ways to conceal the picture

Check out the JSfiddle link here for the full code. I'm having trouble with my slider as the last picture keeps collapsing underneath and is not hidden as it should be. I suspect this issue is causing the slider to malfunction. HTML <div class=" ...

Achieve video lazy loading in JavaScript or jQuery without relying on any external plugins

I've been experimenting with lazy loading videos using jQuery. While I've had success with lazy loading images and background-images using the same technique, I ran into issues when trying to apply it to videos. Here's what I've tried s ...

Issue with cross-origin in Salesforce reply (Access-Control-Allow-Origin)

While attempting to retrieve records from Salesforce using external local files via JS, I encountered an issue. Although I can see a response in the network tab, the console displayed the following error message: "XMLHttpRequest cannot load . No 'A ...

Display the DIV specifically for visitors arriving from Facebook

I want to display a specific DIV on the product page only if the user has visited from Facebook. Currently, I am using the following code to check if they arrived from Facebook: var ref = document.referrer; if (ref.match(/^https?:\/\/([^\ ...

Formatting a pair of elements side by side in MUI Select

Currently, I am tackling the challenge of organizing elements in MUI Select v4. My goal is to display these elements in two columns rather than just one column within the dropdown. Despite attempting to override certain styles within MUI, I have not been ...

Enhanced jQuery Embed Code validation for user input using a textarea

Currently, I am developing a website that allows users to input embed codes from popular platforms such as Twitter, YouTube, Instagram, Facebook, and so on. The embed code undergoes validation checks and is saved if it meets the criteria. However, when us ...