Website remember button press - javascript

I have a problem with to get my website remember a button press. Website automatically plays music and it has mute button, but it doesn't remember if you pushed the button when you go to next page or refresh the page. That local storage script doesn't seem to work.
function mute(){
var audio = document.getElementById("music")
var toggle = document.getElementById("toggle")
if (audio.muted == true) {
audio.muted=false
toggle.innerHTML ="MUTE"
} else {
audio.muted=true
toggle.innerHTML ="UNMUTE"
}
}
<audio id="music" autoplay loop>
<source src="/files/music.mp3" type="audio/mpeg">
<source src="/files/music.ogg" type="audio/ogg"> Your browser does not support the audio element.
</audio>
<script>
var audio = document.getElementById("music");
audio.volume = 0.3;
</script>
<button id="toggle" class="toggle" onclick="mute()">MUTE</button>
<script>
localStorage.setItem('toggle', 'true');
localStorage.getItem('toggle'); // returns 'true'
</script>

Your original script is setting 'toggle' to true every time the page refreshes.
This should work as expected, see in JSFiddle (try press Run again after clicking the button to confirm it correctly stores the value): https://jsfiddle.net/kevinkassimo/m44vh2qy/
(the following code would not work due to snippet sandboxed environment)'
<button id="toggle" class="toggle" onclick="toggle()">TOGGLE</button>
<h1 id="txt"></h1>
<script>
function toggle() {
let isToggle = +localStorage.getItem('toggle');
if (!isToggle) {
localStorage.setItem('toggle', 1);
document.getElementById('txt').innerHTML = 'Toggled';
} else {
localStorage.setItem('toggle', 0);
document.getElementById('txt').innerHTML = 'Not Toggled';
}
}
document.addEventListener("DOMContentLoaded", function(event) {
if (+localStorage.getItem('toggle')) {
document.getElementById('txt').innerHTML = 'Toggled';
} else {
document.getElementById('txt').innerHTML = 'Not Toggled';
}
})
</script>
A working sample is here:
https://jsfiddle.net/kevinkassimo/a9o6mjnw/16/

Your IF statement checks for the Boolean of TRUE, but your local storage variable is set to the string “true”

Related

How to play an audio file without it opening in a new tab

I would like to implement an audio player on all of my WordPress pages and therefore I need to create the HTML element with JS and manipulate it from there. Everything is working, except for when I press the play button, it redirects me to a new page with the audio link and plays it there. I would like to prevent that, so that I can play and stop it on the WP pages themselves and have the audio play in the background.
Any tips are greatly appreciated!
function addAudioPlayer() {
const audioPlayer = document.createElement("a");
audioPlayer.setAttribute("id", "audioPlayer");
audioPlayer.href =
"https://www.hostname.com/wp-content/uploads/2020/09/bird_sound.wav";
audioPlayer.setAttribute("data-id", "[data-song]");
audioPlayer.innerHTML = "▶";
Array.prototype.forEach.call(
document.querySelectorAll("[data-song]"),
function (song) {
song.audio = new Audio(song.href);
song.setAttribute("role", "button");
song.setAttribute("aria-pressed", "false");
}
);
document.addEventListener("click", function (event) {
if (!event.target.hasAttribute("data-song")) return;
event.preventDefault();
if (event.target.getAttribute("aria-pressed") == "true") {
event.target.audio.pause();
event.target.setAttribute("aria-pressed", "false");
return;
}
event.target.audio.play();
event.target.setAttribute("aria-pressed", "true");
},
false
);
document.body.appendChild(audioPlayer);
}
<div>
<audio id="myaudio" src="https://www.hostname.com/wp-content/uploads/2020/09/bird_sound.wav" controls="controls" preload="auto" hidden="true"></audio>
<input type="button" onclick="autoPlay()" value="Play"/>
</div>
<script language="javascript" type="text/javascript">
var myAuto = document.getElementById('myaudio');
function autoPlay(){
myAuto.play();
}
</script>

Play audio using button and restart to the beginning when the button is clicked again

I'm making several button that if I clicked it plays designated sounds each button, and stop the sounds if I clicked another button and plays that sound. And if I click again the button, the sound will repeat to the beginning. Thanks :)
javascript
$(document).ready(function(){
$('#menuIcon').mouseover(function(e) {
$('.bar1').addClass("hovered");
$('.bar2').addClass("hovered");
$('.bar3').addClass("hovered");
});
$('#menuIcon').mouseout(function () {
$(".bar1").removeClass("hovered");
$(".bar2").removeClass("hovered");
$(".bar3").removeClass("hovered");
});
});
function myFunction(x) {
x.classList.toggle("change");
$('.dropdown-menu').toggle();
}
function playSound() {
var sound= new Audio('sound campaign/10,000 Reasons.mp3');
sound.currentTime = 0
sound.play();
}
HTML
<input type="button" value="10,000 Reasons" onclick="playSound()" />
You should use the sound.pause(); to pause it.
If you would like to use multiple audios, you should use the HTML audio tag.
It would allow you to pause all of them at once.
example:
<input type="button" value="10,000 Reasons" onclick="playSound(0)" />
<audio src="sound campaign/10,000 Reasons.mp3" autoplay loop>
</audio>
function playSound(e) {
var sounds = document.getElementsByTagName('audio');
for(i=0; i<sounds.length; i++) sounds[i].pause();
var sounds = document.getElementsByTagName('audio')[e];
sound.currentTime = 0
sound.play();
}

Javascript audio play on click and stop on click

Current code:
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<button class="matrixBtn" value="PLAY" onclick="play()">star shopping</button>
<audio id="audio" src="xxx"></audio>
When I press the button the music starts, which is exactly what I want. But I also want if I press the button again that the music stops. How can I do this without create a second button?
the <audio> tag is a HTMLMediaElement, so it has a property .paused which you can use to determine the current state and act accordingly:
function playPause() {
var audio = document.getElementById("audio");
if(audio.paused)audio.play();
else audio.pause();
}

Mute/unmute button for background sound

guys. Please explain this to me.
I wanted to create a single mute/unmute button for my page. (audio starts automatically)
So here the code I used first time:
<script>
var sound = getElementById (‘background_sound’);
function mute(){
if(background_audio.muted == false){
background_audio.muted = true;
} else {
background_audio.muted = false;
}
}
</script>
But it didn’t work. So I just removed the first line (I mean this var) and addressed the id directly. And it worked. Now my html looks like this:
<audio id="background_audio" autoplay="true" loop="loop">
<source src="Audio/flute.mp3">
If you are reading this, it is because your browser does not support the audio element.
</audio>
<button onclick="mute()">
<i class="fa fa-music"></i></button>
And javascript like this
<script>
function mute(){
if(background_audio.muted == false){
background_audio.muted = true;
} else {
background_audio.muted = false;
}
}
</script>
The question is how can I address Id directly without creating a variable? It works fine though but will I have any problems with the code later? I just thought I need to assign a var this to work. A bit confused.
try this i am sure this will work
<script>
function mute(){
if(document.getElementById('background_audio').muted == false){
document.getElementById('background_audio').muted = true;
} else {
document.getElementById('background_audio').muted = false;
}
}
</script>

Play one HTML audio element at a time

I have many audio elements on a single page and I want to play just one element at a time. That is if one audio element is playing and I click on play on another element, the previous audio element should pause.
I found a jQuery code from another question to do this but that uses an image as play/pause controls. I'm using the inbuilt controls='controls' attribute for the audio element instead. Is it possible to use jQuery to control the play/pause feature for the audio element in my case?
Here is my HTML code
<div>
<p class="song"><h3><strong>#1 Intro - The Oath</strong></h3><p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
<div>
<p class="song"><h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3></p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
Here is the jQuery code
$(document).ready(function() {
var curPlaying;
$(function() {
$(".playback").click(function(e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if(song.paused){
song.play();
if(curPlaying) $("audio", "#"+curPlaying)[0].pause();
} else { song.pause(); }
curPlaying = $(this).parent()[0].id;
});
});
});
The jQuery code doesn't seem to be working for me.
$(function(){
$("audio").on("play", function() {
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
});
See sample at JSFiddle
Vanilla JS solution
Here's a solution that doesn't require jQuery.
function onlyPlayOneIn(container) {
container.addEventListener("play", function(event) {
audio_elements = container.getElementsByTagName("audio")
for(i=0; i < audio_elements.length; i++) {
audio_element = audio_elements[i];
if (audio_element !== event.target) {
audio_element.pause();
}
}
}, true);
}
document.addEventListener("DOMContentLoaded", function() {
onlyPlayOneIn(document.body);
});
Some things to note:
Because this listens for events on a parent element, not on the audio elements themselves, they can be added or removed after the page is loaded and it will still work.
It watches for the play event in the capture phase because play events don't bubble.
More media events are described here on MDN.
Listening for "DOMContentLoaded" should work for most browers.
Little Modification to LostInComputer's Answer
In Your HTML Write:
<audio controls onplay="pauseOthers(this);" >
<source src="SourcePath">
</audio>
In Js Write:
function pauseOthers(ele) {
$("audio").not(ele).each(function (index, audio) {
audio.pause();
});
}
Assuming that your syntax for stopping and pausing tracks is correct (I don't know anything about the audio element), you should be able to do something like this:
$(".playback").click(function(e) {
// pause all other tracks
$('.audio').each(function () {
var song = this;
if (!song.paused) { song.pause(); }
});
// play the audio associated with this element
this.play();
});
<script>
function controlplay(e) {
document.querySelectorAll('.playback').forEach(item => { if(item.id != e.target.id) item.pause(); });
}
</script>
<script>
document.querySelectorAll('.').forEach(item => { item.addEventListener("play", event => { controlplay(event) })});
</script>
Angular:
<audio (play)="audioPlay($event)" controls preload="none">
<source [src]="url" type="audio/mpeg">
</audio>
audioPlay(e) {
let eAudio = this.domService.getDocument.getElementsByTagName('audio')
if (eAudio && eAudio.length > 0) {
for (var i = 0; i < eAudio.length; i++) {
if(e.target !== eAudio[i]){
eAudio[i].pause();
}
}
}
}
<script>
var nowplaying = null;
// Pause and reset playing audio before starting new selection
function pauseRunningAudio(id) {
if ( nowplaying != null && nowplaying != id) {
var x = document.getElementById(nowplaying);
x.pause();
x.load();
}
nowplaying = id;
}
</script>
<!-- id and function value must be the same -->
<audio controls onplay="pauseRunningAudio('song1')" id="song1">
<source src="Bohemian Rhapsody.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song2')" id="song2">
<source src="November Rain.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song3')" id="song3">
<source src="Smoke on the Water.mp3" type="audio/mpeg">
</audio>

Categories

Resources