hide and display a div using javascript in ASP.NET - javascript

I want display an audio player, after click a button. here my code
<script type="text/javascript">
function viewAudio() {
document.getElementById('myAudio').style.display = ""
}
document.getElementById('myAudio').style.display = "none"
</script>
<button value="#Html.DisplayFor(modelItem => item.SampleURL)" id="audioViewer" onclick="viewAudio()">
<img src="../../Content/images/audio.png"></button>
<div id="myAudio">
<audio controls preload="none">
<source src="#" type="audio/mp3">
</audio>
</div>
But, when i run in browser it still display the audio player.
any solution for this?

First of all, to have the player hidden by default you don't need to use JavaScript. Add such style to the container instead:
<div id="myAudio" style="display: none;">
And to show it back upon clicking the button:
function viewAudio() {
document.getElementById('myAudio').style.display = "block";
}

If this is an ASP page then that button click might be doing a postback. This will reset the state. You should have either return false; at the end of the onclick.
Alternatively, if the problem is that the div is never hidden, you can set the style directly on the div element in the html markup.
Make sure that you are using your browser's development tools to check the css styling currently on the element you're looking at. You can also set breakpoints and step through your javascript code, right in your browser.

<asp:Button ID="ButtonShowPanel" CausesValidation="false" CssClass="btn btn-primary pull-right" runat="server" Text="Add Contact" OnClientClick="javascript:SetVisiblityPanels(false); return false;" />
function SetVisiblityPanels(check) {
if (check) {
$('.SearchPanel').show(1000);
$('.DescriptionPanel').hide(1000);
}
else {
$('.SearchPanel').hide(1000);
$('.DescriptionPanel').show(1000);
}
}

<script type="text/javascript">
function CheckVisiblityPanels(check) {
if (check) {
{
document.getElementById('<%=myAudio.ClientID%>').style.display = "block";
}
else
{
document.getElementById('<%=myAudio.ClientID%>').style.display = "none";
}
return false;
}
};
</script>

Related

How to build a button to click on and play / stop an audio?

i want to build a image button, that plays an audio.
My Version works but when I want to use it more than once on a site, it only play one mp3, not the other ones.
My Code:
<audio loop="false" src="audio_01.mp3"> </audio>
<p><img alt="" class="hover_pic" src="image.png" style="width: 40%;cursor:pointer" /></p>
<script>
var aud = document.getElementById("ASong").children[0];
var isPlaying = false;
aud.pause();
function playPause() {
if (isPlaying) {
aud.pause();
} else {
aud.play();
}
isPlaying = !isPlaying;
}
</script></div>
and
<div id="BSong" onclick="playPause()" type="button">
<audio loop="false" src="audio_02.mp3"> </audio>
<p><img alt="" class="hover_pic" src="image.png" style="width: 40%;cursor:pointer" /></p>
<script>
var aud = document.getElementById("BSong").children[0];
var isPlaying = false;
aud.pause();
function playPause() {
if (isPlaying) {
aud.pause();
} else {
aud.play();
}
isPlaying = !isPlaying;
}
</script></div>
So you have an idea what the problem is that the button only play one of them on the website?
You are using the same variable names multiple times like aud, isPlayig, etc..
To solve this issue, you should declare only once the whole script and form the onclick="playPause()" send the id of the song you want to play.
Be aware if there is already some music which is playing.
It's hard to tell how your two current code snippets are arranged with respect to each other, but duplicating the code over and over every time you want to add another track is going to be unmaintainable. As it stands, the variables for isPlaying and aud probably overwrite each other, depending on how they're laid out, even if they're in different scripts. Using const or let instead of var and use strict; at the top of your script can help detect these aliases.
You could add closures around each one to keep them distinct, but a better approach is to write a loop (which also acts as a scoping closure) and dynamically add the listener to each element. For example:
const trackEls = [...document.querySelectorAll(".track")];
for (const trackEl of trackEls) {
const audioEl = trackEl.querySelector("audio");
trackEl.addEventListener("click", () => {
audioEl.paused ? audioEl.play() : audioEl.pause();
});
}
<div class="tracks">
<div type="button" class="track">
<audio src="https://upload.wikimedia.org/wikipedia/commons/d/d8/Bourne_woods_2020-11-18_0732.mp3"></audio>
<img alt="play track icon" src="http://placekitten.com/50/50" class="track-icon">
</div>
<div type="button" class="track">
<audio src="https://upload.wikimedia.org/wikipedia/commons/e/ea/Rapid-Acoustic-Survey-for-Biodiversity-Appraisal-pone.0004065.s017.ogg"></audio>
<img alt="play track icon" src="http://placekitten.com/50/50" class="track-icon">
</div>
</div>
Note that the above code lets multiple audio files play at once. If you want to stop all other audio elements when a new one is clicked and reset their time, you can do that with a loop or an extra variable that keeps track of the currently-playing track. For example:
const trackEls = [...document.querySelectorAll(".track")];
let currentTrack;
for (const trackEl of trackEls) {
const audioEl = trackEl.querySelector("audio");
trackEl.addEventListener("click", () => {
if (audioEl !== currentTrack) {
if (currentTrack) {
currentTrack.pause();
currentTrack.currentTime = 0;
}
currentTrack = audioEl;
}
audioEl.paused ? audioEl.play() : audioEl.pause();
});
}
<div class="tracks">
<div type="button" class="track">
<audio src="https://upload.wikimedia.org/wikipedia/commons/d/d8/Bourne_woods_2020-11-18_0732.mp3"></audio>
<img alt="play track icon" src="http://placekitten.com/50/50" class="track-icon">
</div>
<div type="button" class="track">
<audio src="https://upload.wikimedia.org/wikipedia/commons/e/ea/Rapid-Acoustic-Survey-for-Biodiversity-Appraisal-pone.0004065.s017.ogg"></audio>
<img alt="play track icon" src="http://placekitten.com/50/50" class="track-icon">
</div>
</div>
A few remarks on your code:
There's no need for isPlaying variables since audio elements already track their playing/paused state with audioElement.paused. If you track it in external state, you add further complication and room for bugs if your variable and the the audio element's state go out of sync.
Avoid putting a <script> in a <div>. <script> is usually a child of <body> or <head> (probably <body> in this case), after all of the HTML tags are closed.
onclick on an HTML element is generally poor practice. HTML should be structural, not behavioral. Similarly, style="width: 40%;cursor:pointer" should be moved to an external stylesheet and applied to a class.
.children[0]; is a brittle way to select the audio element in a track. If you wind up rearranging elements in the div, this code is liable to break. document.querySelector("#BSong audio") is more precise and robust to refactors, although using classes instead of ids enables easier dynamism so you don't have to type each track out by hand.
CSS classes are usually kebab-case, so hover_pic would be hover-pic.

Stop audio on click and play it again

I am using 2 custom buttons and using JavaScript to click the audio play and pause.
I am using the below code for that:
<img class="head-iconn" src="img/audio.png" onClick="document.getElementById('audio1_play32').play(); return false;" />
<img class="head-icon2" src="img/audio2.png" onClick="document.getElementById('audio1_play32').pause(); return false;" />
But I want to stop the audio instead of pause so that when I play it again, it'll start from the beginning.
I am using this code for that:
<img class="head-iconn" src="img/audio.png" onClick="document.getElementById('audio1_play32').play(); return false;" />
<img class="head-icon2" src="img/audio2.png" onClick="document.getElementById('audio1_play32').pause(); document.getElementById('audio1_play32').currentTime = 0;return false;" />
and now the audio stops but can not play again when I click on the first button.
This is the audio code I am using:
<audio id="audio1_play32" controls>
<source src="voice/vo1.mp3" type="audio/mp3"/>
</audio>
Can someone please let me know what I am making mistake?
Thank you.
Update
Although not part of the question OP asked,
"What is I have multiple audios on a single page?"
Simply place the event handler on an element that contains all of the <button>s. Then get the reference to a specific <audio> by proximity of clicked <button>(event.target):
<audio><!--mp3 = btnGroup.previousElementSibling--></audio>
<fieldset>
<!--btnGroup = clicked.parentElement-->
<button><!--clicked = event.target--></button>
</fieldset>
Stay away from using attribute event handlers:
<!-- This is bad -->
<button class='play' onclick='playAudio()'>PLAY</button>
Use .addEventListener()
<button class='play'>PLAY</button>
<script>
const play = document.querySelector('.play');
play.addEventListener('click', playAudio);
</script>
or property event handlers:
<button class='play'>PLAY</button>
<script>
const play = document.querySelector('.play');
play.onclick = playAudio;
</script>
See Event Handlers
Keep your JavaScript separate from HTML or you'll cripple the growth of your code. The example below uses event delegation to determine which button was clicked and what happens according to what was clicked.
const main = document.querySelector('main');
const audioControl = event => {
const clicked = event.target;
const btnGroup = clicked.parentElement;
const mp3 = btnGroup.previousElementSibling;
if (clicked.matches('.play') && !mp3.paused) {
mp3.pause();
} else if (clicked.matches('.play') && !mp3.playing) {
mp3.play();
} else if (clicked.matches('.stop')) {
mp3.pause();
mp3.currentTime = 0;
} else {
return false;
}
};
main.onclick = audioControl;
button {
border: 0;
cursor: pointer;
font-size: 4ch
}
fieldset {
display: inline-block;
}
<main>
<audio src='https://soundbible.com/mp3/thunder_strike_1-Mike_Koenig-739781745.mp3'></audio>
<fieldset>
<button class='play'>⏯️</button>
<button class='stop'>⏹️</button>
</fieldset>
<audio src='https://soundbible.com/mp3/airplane-landing_daniel_simion.mp3'></audio>
<fieldset>
<button class='play'>⏯️</button>
<button class='stop'>⏹️</button>
</fieldset>
<audio src='https://soundbible.com/mp3/old-car-engine_daniel_simion.mp3'></audio>
<fieldset>
<button class='play'>⏯️</button>
<button class='stop'>⏹️</button>
</fieldset>
</main>

Pausing another song when starting another javascript

I'm trying to make it so that when you click on a separate element it pauses the current song playing from a different element. In addition I had previously made it so when you click on the same element after it started playing audio it would pause that audio, but when you click on a different element with the same function it breaks.
var paused = true;
var song;
var songPlaying;
function playSong(x) {
song = x;
if(songPlaying != song){
document.getElementById(songPlaying).pause();
}
if(paused == true){
document.getElementById(song).play();
paused = false;
songPlaying = song;
} else {
document.getElementById(song).pause();
paused = true;
}
}
Is there anyway I can fix this? Will I have to make a different function for every song?
EDIT 1: Here the HTML my for the sections I'm using as well, each audio file has an ID that is called as a parameter in the function inside onclick
<div class="album">
<img src="assets/BattalionsOfFear.png" onclick="playSong('bofSong')">
<h1>Battalions of Fear</h1>
<p>Released in 1988</p>
</div>
<div class="album">
<img src="assets/FollowTheBlind.png" onclick="playSong('bfsSong')">
<h1>Follow the Blind</h1>
<p>Released in 1989</p>
</div>
<!--- Audio -->
<audio id="bofSong">
<source src="assets/BattalionsOfFear.mp3">
</audio>
<audio id="bfsSong">
<source src="assets/BanishFromSanctuary.mp3">
</audio>
EDIT 2:
In attempting Laif's solution
I have tried adding the 'song' class to my HTML img elements and linked it to my audio element with the 'song1' class yet it still is not working. Am I doing the classes wrong or is it something with the way I have put them down?
<div class="album">
<img src="assets/BattalionsOfFear.png" class="song song1">
<h1>Battalions of Fear</h1>
<p>Released in 1988</p>
</div>
<audio id="bofSong" class="song1">
<source src="assets/BattalionsOfFear.mp3">
</audio>
Each song should share the same class so that you can do something like this:
<html>
<div class="song"></div>
<div class="song"></div>
</html>
var songs = document.querySelectorAll(".song");
function playSong(e) {
songs.forEach(el => {
el.style.play();
});
e.currentTarget.pause();
};
songs.forEach(el => {
el.addEventListener("click", playSong);
});

Preventing child click event from triggering its parent event

I have a video tag which is placed inside an asp.net LinkButton control. The button fires some event when clicked. If the user clicks the video, both the video event (playing the video) and the button event fire. I only want the video to play.
I found different solutions on the web, but they didn't work.
Here is my javascript code:
<script type="text/javascript">
function play(e)
{
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
/*$(".pVideo").click(function (event) {
if (event.target == this) {
event.stopPropagation();
}
});*/
</script>
This is the video tag which is placed inside a LinkButton (it's placed inside a label, but I think that's not a problem because a label has no onclick event):
<asp:Label runat="server" Visible="false" ID="videoHolder">
<video controls="true" id="pVideo" onclick="play()">
<source src='<%# !String.IsNullOrEmpty(Eval("postVideo2").ToString()) ? "/uploadedVideos/" + Eval("postVideo2"): "" %>' type="video/mp4"/>
</video>
</asp:Label>
When calling play function I get this error in JS: "no element found", but I couldn't figure out the reason. Please notice that I also tried the commented JQuery function after adding the required resources, but I kept getting error saying that $ is not defined.
Edit: This is how I did it for JQuery, but still not working:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js">
$("#pVideo").click(function () {
if (event.target == this) {
event.stopPropagation();
}
});
</script>
Video tag:
<asp:Label runat="server" Visible="false" ID="videoHolder">
<video controls="true" id="pVideo">
<source src='<%# !String.IsNullOrEmpty(Eval("postVideo2").ToString()) ? "/uploadedVideos/" + Eval("postVideo2"): "" %>' type="video/mp4"/>
</video>
I'm getting "no element found" error.
Can anyone please tell me how to play the video without firing the parent LinkButton event?
Thanks.

Remove an image brought up by on mouseover

The following script opens an image onmouseover, however I can't come up with a way to remove the image onmouseout. I know I am missing something extremely simple but can't seem to find something that works.
<script type="text/javascript">
function show(Id) {
document.getElementById(Id).style.display="inline";
}
</script>
<span onmouseover="show ('myImage')">- <u>LAZARETTE</u></span></b>
<img src="../images/MarkILineDrawingLazarette.jpg" id="myImage" border="0" style="display:none;"
You are very close! Just add the onmouseout event!
HTML
<b>
<span onmouseover="show('myImage',true)" onmouseout="show('myImage',false)">- <u>LAZARETTE</u></span></b>
JAVASCRIPT
function show(Id, show) {
document.getElementById(Id).style.display = show ? "inline" : "None";
}
function hide(Id) {
document.getElementById(Id).style.display="none";
}
then change the opening span tag to:
<span onmouseover="show('myImage')" onmouseout="hide('myImage')" >
Edit:
JSFiddle!

Categories