Disable and re-enable a function, Mute and Unmute - javascript

Hi I am trying to disable a function with a click of a button and then enable it again once another button is clicked I have tried unbind but I am getting no where
any suggestions to how I can go about this?
Code:
Mute
Unmute
$('.MuteOn').on('click tap touch', function() {
//Disable soundListen function
});
$('.MuteOff').on('click tap touch', function() {
//Enable soundListen function
});
//
setInterval(function soundListen() {
if ($("body").hasClass("fp-viewing-1")) {
audio1.play();
} else {
audio1.pause();
audio1.currentTime = 0;
}
if ($("body").hasClass("fp-viewing-2")) {
audio2.play();
} else {
audio2.pause();
audio2.currentTime = 0;
}
if ($("body").hasClass("fp-viewing-3")) {
audio3.play();
} else {
audio3.pause();
audio3.currentTime = 0;
}
}, 100);
Thank you in advance for any suggestions.

Ok, so I understood it like this:
-On first page user can click mute/unmute button and that should be saved during navigation through all other pages/slides.
Then here is a code:
<!doctype>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<button id="mute">Mute</button>
<button id="unmute">Unmute</button>
<button id="reloadPage">Reload Page</button>
<script type="text/javascript">
//get variable from local variables or set to false(you can change it to TRUE if you like to mute on page load) by default
var isMuted = localStorage.getItem("IsMuted")||false;
//mute button onclick method
$(document).on('click','#mute',function(e){
isMuted = true;
//save to local variables
localStorage.setItem("IsMuted", isMuted);
});
//unmute button onclick method
$(document).on('click','#unmute',function(e){
isMuted = false;
//save to local variables
localStorage.setItem("IsMuted", isMuted);
});
//reload page. also you can use F5 or Ctrl+F5
$(document).on('click','#reloadPage',function(e){
location.reload();
});
$(document).ready(function(){
alert("IsMuted = "+isMuted);
//you can encapsulate this into separate function and bind to show-next-slide button
if(isMuted)
{
return;
}
else
{
//get clip id by class name or another suitable method
PlayMyCoolMusic(clipId);
}
});
function PlayMyCoolMusic(clipId)
{
//your audio player logic here
}
</script>
</body>
</html>
With this you can save you mute/unmute status even if page has been reloaded.

Related

How do I make an audio file play with JavaScript when a web page is loaded?

I want an audio file to play automatically when a web page loads. I've tried the following simple code but for some reason it's not working. Any thoughts? I understand this may be caused by some default behavior of Google Chrome. Thanks.
<!DOCTYPE html>
<html>
<head>
<title>My Audio</title>
</head>
<body>
<script type="text/javascript">
window.onload=function(){
const audio = new Audio("wonderful.mp3");
audio.play();
}
</script>
</body>
</html>
Simply you can't.
Browsers don't allow you to play audio when the user has not interacted with your site at least once.
You should create a simple function that, when the user click for the first time on your page, play your audio.
Error : Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
This snippet allows you to play your audio when the user click on your document for the first time :
<!DOCTYPE html>
<html>
<head>
<title>My Audio</title>
</head>
<body>
<div>Test</div>
<audio id="my-audio" autoplay
src="https://file-examples.com/storage/fe8bd9dfd063066d39cfd5a/2017/11/file_example_MP3_5MG.mp3"></audio>
<script type="text/javascript">
var isAudioPlayed = false;
function playAudio() {
isAudioPlayed = true;
const myAudio = document.getElementById("my-audio");
myAudio.play();
}
document.body.onclick = ()=>{
if(isAudioPlayed) return ;
playAudio();
}
/*
window.onload = () => {
const myAudio = document.getElementById("my-audio");
console.log(myAudio);
myAudio.addEventListener('canplay', (event) => {
console.log("CnPlay",event)
event.target.play()
})
}
*/
</script>
</body>
</html>
Else you can use canplay event

How "beforeunload" and "unload" events work?

As I understood correctly when user closes a tab or clicks on the link or, even, updates a page "beforeunload" and then "unload" events are triggered. First, I can't register an event handler (some code snippets doesn't work):
From MDN web docs example I have written the following:
window.addEventListener("beforeunload", function (event) {
event.preventDefault();
event.returnValue("Are you sure?");
});
and it doesn't work (I expected dialog appearance)
Also I have tried this:
window.addEventListener("beforeunload", function (event) {
return "Are you sure?";
});
and it doesn't work as well
From w3school docs I have written:
window.onbeforeunload = function () {
return "Are you sure?";
}
and it work! But why the previous doesn't work?
How about triggering on browser or tab closing? Is it possible "to do some operations" when the user closes tab or browser? To be more clear, I want to delete some cookies which refers to his current session when the user closes tab or browser. Or I need to do something like this?
window._link_was_clicked = false;
window.onbeforeunload = function(event) {
if (window._link_was_clicked) {
return; // abort beforeunload
}
// your event handling
};
jQuery(document).on('click', 'a', function(event) {
window._link_was_clicked = true;
});
Here is full demo code which I have written:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.4/angular.min.js"></script>
<script>
angular
.module("app", [])
.controller("Controller", function ($scope) {
$scope.username = localStorage.getItem("username") || "";
$scope.setCookie = function () {
console.log("Set Cookie");
localStorage.setItem("username", "Denys");
$scope.username = localStorage.getItem("username");
}
$scope.deleteCookie = function () {
console.log("Delete Cookie");
localStorage.removeItem("username");
$scope.username = localStorage.getItem("username") || "";
}
})
.run(function () {
console.log("run()");
window.addEventListener("beforeunload", function (event) {
event.preventDefault();
event.returnValue("Are you sure?");
return "Are you sure?";
});
window.addEventListener("unload", function (event) {
localStorage.removeItem("username");
});
window.onbeforeunload = function () {
return "Are you sure?";
}
});
</script>
</head>
<body ng-controller="Controller">
<h1>Hello!</h1>
<p ng-if="username">{{username}}</p>
<p>
<button ng-click="setCookie()">Set Cookie</button>
<button ng-click="deleteCookie()">Delete Cookie</button>
</p>
</body>
</html>
You have added parentheses in the first one even though there aren't any in the MDN documentation:
The event should also fire if the tab is closed.
If you set the cookie expiration correctly you can make it so they delete automatically.

A simple example using html, javascript and jQuery

I'm starting with javascript, websockets and jQuery developing a simple example. In the html page I only have a button, that, when pressed, has to send its state (ON/OFF for instance). In index html, I have the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>
<title>First App</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/APP.js"></script>
</head>
<body>
<div id='hello_message'>
Connecting...
</div>
<button id='state'>Turn on</button>
<div id='off'>OFF</div>
<div id='on'>ON</div>
</body>
</html>
My intention is to open a websocket between the client and the server when the page is loaded, and keep it open for any information to be sent between both of them. To this end, I have the following file containing the js code (APP.js):
window.onload = APPStart;
// Page onload event handler
function APPStart() {
state = false;
if ("WebSocket" in window)
{
var ws = new WebSocket("ws://10.30.0.142:8020");
ws.onopen = function()
{
alert ("Connected");
$('#hello_message').text("Connected");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
};
ws.onclose = function()
{
alert("Connection is closed...");
};
window.onbeforeunload = function(event) {
socket.close();
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}}
Now, every time someone clicks on button, I would like to execute the following code:
// program checks if led_state button was clicked
$('#state').click(function() {
alert ("click");
// changes local led state
if (led_state == true){
$('#on').hide();
$('#off').show();
state = false;
ws.send("ON");
}
else{
$('#off').hide();
$('#on').show();
state = true;
ws.send("OFF");
}
});
I've tried to put this part of the code inside the function APPStart, but it doesn't work. I also suspect that jQuery is not working either since messages are not updated. Any suggestion to make it work?
Thanks for the comments. The code works, the problem was in the cache of the browser. Once I noticed it, I cleaned the cache and everything started to work. Silly me.

onclick event not firing based on boolean flag

I'm working on some code where if a user clicks on a particular button, that person is NOT presented with an exit popup upon exiting the page. The way I'm doing it is by setting a flag whenever the user clicks on the button. However, my code isn't working as expected: The popup loads whether or not the button is clicked. I don't understand why.
Edit: Help!
<!doctype html>
<html>
<head>
<title>Test!</title>
<script>
var bool = false;
var config = new Object();
config.surveyID = 3155031;
config.takeSurveyURL = 'http://www.supporterfeedback.org/a/TakeSurvey';
config.windowPositionLeft = 200;
config.windowPositionTop = 300;
config.home = 'http://www.surveyanalytics.com/';
config.isRightToLeft = false;
config.showFooter = true;
// document.getElementById("btn").onclick = function()
// {
// bool = true;
// };
function flag() {
bool = true;
}
if (!bool) {
window.onbeforeunload = function () {
QP_popupMain();
};
}
</script>
<script language="javascript"
src="http://www.surveyanalytics.com//javascript/exitSurveyInvitation.js"
type="text/javascript"></script>
<noscript>
Start Survey
</noscript>
</head>
<body>
<a href="http://google.com"><img id="btn" onclick="flag()"
src="http://kelowna.directrouter.com/~jeasprco/wp-content/uploads/2012/05/PanicButton2.png"/></a>
<p>Hello, this is a test!</p>
</body>
</html>
I think window.onbeforeunload = function () is operating as soon as the page loads, so what is inside if(!bool) is executing on the button press.
Try changing these two lines:
// var bool = false;
var bool;
// if (!bool) {
if (bool == false) {
You're testing the flag once, when you assign the .beforeunload handler when the page is loaded. Calling flag() doesn't re-execute that code. You need to test it when the function is called.
window.onbeforeunload = function() {
if (!bool) {
return "You haven't clicked the button, do you really want to leave?"
}
}

No fullscreen button on YTPlayer toolbar iOS

I'm using YTPlayer in my iOS app. Everything's fine until the fullscreen button on the toolbar of the YTPlayer got disappeared, now I don't see the fullscreen button,
instead I have a video quality button, playlist button and play on youtube button which are not much useful for me, also which weren't there before. So how to get a fullscreen button on the toolbar and if possible how to remove unwanted buttons. Should I have to change anything in the html file?
<!DOCTYPE html>
<html>
<head>
<style>
body { margin: 0; width:100%%; height:100%%; }
html { width:100%%; height:100%%; }
</style>
</head>
<body>
<div id="player"></div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
YT.ready(function() {
player = new YT.Player('player', %#);
window.location.href = 'ytplayer://onYouTubeIframeAPIReady';
});
function onReady(event) {
window.location.href = 'ytplayer://onReady?data=' + event.data;
}
function onStateChange(event) {
window.location.href = 'ytplayer://onStateChange?data=' + event.data;
}
function onPlaybackQualityChange(event) {
window.location.href = 'ytplayer://onPlaybackQualityChange?data=' + event.data;
}
function onPlayerError(event) {
window.location.href = 'ytplayer://onError?data=' + event.data;
}
</script>
</body>
</html>
Thanks in advance.
Never mind. The fullscreen button is visible now. Have no idea why it disappeared and why it got back, think youtube modified it or something.

Categories

Resources