I have an html audio tag in my project, which in some situation I need to disable.
In order to do it I apply the following css by adding disabled
class to the audio tag:
audio.disabled {
pointer-events: none
}
I would like to add a layer with opacity 50% that will cover the audio element, in order to give a different view for it when it is disabled.
I thought to use the pseudo class ::before
, but do not manage to have a visible element.
Here is a snippet with what I have already:
function toggleAudioDisable() {
document.getElementById('myAudio').classList.toggle("disabled");
}
.disabled {
pointer-events: none
}
<audio id="myAudio" controls="controls" src="https://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg"></audio> <br>
<button onclick="toggleAudioDisable()">Toggle Audio Disable</button>
Any idea how to implement it?
5
Answers
"I would like to add a layer with opacity 50% that will cover the audio element, in order to give a different view for it when it is disabled."
You can do this by adding an ‘opacity’ declaration to your .disabled class.
Use disabled attribute to prevent user interaction with element.
Updated toggleAudioDisable function:
Updated style:
I added a layer with
opacity: 0.5
and it will works as you want. Hope it helps you!Why don’t you style the tag itself "audio"?
Audio elements have the following pseudo-element selectors in CSS:
If this option does not suit you, I recommend creating a div container where you can add .audio-container::before
I second jerad.blair’s answer, but if you were wondering why it isn’t working your way (or need to specify other properties in the future like
background-color
orcontent
), it is because<audio>
acts like a "replaced element". This means the::before
and::after
pseudo-elements will not be displayed if the element loads/renders properly. Read more on the MDN Web DocsThe solution using a
::before
element would require you to layer a non-replaced element in the markup, such as a<div>
. So something like this will work:This is quite a lot of markup and style overhead for simply an extra
opacity
property, but if you need to do anything more complex with the pseudo-element (e.g.,background-color
,content
), you may have to go this route.