Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an image on a button with javascript

I create a music play/pause button with HTML, CSS and Javascript and would like the icon to change when the music is played or paused. Here's the JSFiddle: https://jsfiddle.net/gp7yf1t3/5/

HTML:

<audio id="player">
  <source src='https://audio.jukehost.co.uk/c926ef6560961d5fd02e35e1488a5997e8217bc1/1a1c12c319a' type='audio/mpeg'/>
</audio>

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

CSS:

#button {
 background-image: url(https://i.imgur.com/laKFwvv.png);
 width: 64px;
 height: 64px;
 background-repeat: no-repeat;
 background-position: center;
 border: 0;
 border-radius: 50%;
 background-color: rgba(0,0,0,0.25)
}

#button:active { background-color: rgba(255,255,255,0.25); }

body { background: red; }

The current icon is a pause icon, but it's supposed to be a play icon. I also added "pause" when it's pause but I want to make it an icon instead.

Javascript:

var button = document.getElementById("button");
var audio = document.getElementById("player");

button.addEventListener("click", function(){
  if(audio.paused){
    audio.play();
    button.innerHTML = "test";
  } else {
    audio.pause();
    button.innerHTML = "test";
  }
});

I tried it with symbol characters but it didn't look really nice and would resize because the symbols weren't the same size. I'd like the button to look nice. My only option right now is to add a play/pause button that doesn't change.

like image 890
noo Avatar asked May 16 '26 03:05

noo


1 Answers

You can insert an <img> tag inside the button like so:

button.addEventListener("click", function(){
  if(audio.paused){
    audio.play();
    buttons.innerHTML = '<img src="https://i.imgur.com/laKFwvv.png" />';
  } else {
    audio.pause();
    buttons.innerHTML = '<img src="https://some/play/icon.png" />';
  }
});
like image 81
emare Avatar answered May 18 '26 16:05

emare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!