I have some javascript code that gets executed once somebody enters the konami code, and I want it to play if it isn't playind, and pause if it is playing. My code seems to be just wrong. Please help!
var rick = false;
var audio = new Audio('rick_roll.mp3');
var kkeys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
$(document).keydown(function(e) {
kkeys.push(e.keyCode);
if (kkeys.toString().indexOf(konami) >= 0) {
$(document).unbind('keydown', arguments.callee);
if (rick == false) {
rick = true;
audio.play();
} else if (rick == true) {
rick = false;
audio.stop();
}
}
});
You should be doing something like this:
var rick = false;
var audio = new Audio('rick_roll.mp3');
var kkeys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
$(document).keydown(function(e) {
kkeys.push(e.keyCode);
if (kkeys.toString().indexOf(konami) >= 0) {
kkeys = []; // <-- Change here
if (rick == false) {
rick = true;
audio.play();
} else if (rick == true) {
rick = false;
audio.pause(); // <-- another issue
}
}
});
You're unbinding the event listener after you get the code entered. You should instead clean old data and start waiting for it again.
Related
I'm learning angular and I'm trying to use copy image from clipboard and paste it in html web page.
I found a solution in Javascript that i want to convert to typeScript. But it doesn't work when I test it. It works fine on jsfiddle : http://jsfiddle.net/KJW4E/1739/
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
var CLIPBOARD = new CLIPBOARD_CLASS("my_canvas", true);
/**
* image pasting into canvas
*
* #param {string} canvas_id - canvas id
* #param {boolean} autoresize - if canvas will be resized
*/
function CLIPBOARD_CLASS(canvas_id, autoresize) {
var _self = this;
var canvas = document.getElementById(canvas_id);
var ctx = document.getElementById(canvas_id).getContext("2d");
var ctrl_pressed = false;
var command_pressed = false;
var paste_event_support;
var pasteCatcher;
//handlers
document.addEventListener('keydown', function (e) {
_self.on_keyboard_action(e);
}, false); //firefox fix
document.addEventListener('keyup', function (e) {
_self.on_keyboardup_action(e);
}, false); //firefox fix
document.addEventListener('paste', function (e) {
_self.paste_auto(e);
}, false); //official paste handler
//constructor - we ignore security checks here
this.init = function () {
pasteCatcher = document.createElement("div");
pasteCatcher.setAttribute("id", "paste_ff");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;width:10px;margin-left:-20px;';
document.body.appendChild(pasteCatcher);
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (paste_event_support === true || ctrl_pressed == false || mutation.type != 'childList'){
//we already got data in paste_auto()
return true;
}
//if paste handle failed - capture pasted object manually
if(mutation.addedNodes.length == 1) {
if (mutation.addedNodes[0].src != undefined) {
//image
_self.paste_createImage(mutation.addedNodes[0].src);
}
//register cleanup after some time.
setTimeout(function () {
pasteCatcher.innerHTML = '';
}, 20);
}
});
});
var target = document.getElementById('paste_ff');
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);
}();
//default paste action
this.paste_auto = function (e) {
paste_event_support = false;
if(pasteCatcher != undefined){
pasteCatcher.innerHTML = '';
}
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
paste_event_support = true;
//access data directly
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
//image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
this.paste_createImage(source);
}
}
e.preventDefault();
}
else {
//wait for DOMSubtreeModified event
//https://bugzilla.mozilla.org/show_bug.cgi?id=891247
}
}
};
//on keyboard press
this.on_keyboard_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey) {
if (ctrl_pressed == false)
ctrl_pressed = true;
}
//v
if (k == 86) {
if (document.activeElement != undefined && document.activeElement.type == 'text') {
//let user paste into some input
return false;
}
if (ctrl_pressed == true && pasteCatcher != undefined){
pasteCatcher.focus();
}
}
};
//on kaybord release
this.on_keyboardup_action = function (event) {
//ctrl
if (event.ctrlKey == false && ctrl_pressed == true) {
ctrl_pressed = false;
}
//command
else if(event.metaKey == false && command_pressed == true){
command_pressed = false;
ctrl_pressed = false;
}
};
//draw pasted image to canvas
this.paste_createImage = function (source) {
var pastedImage = new Image();
pastedImage.onload = function () {
if(autoresize == true){
//resize
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
}
else{
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage.src = source;
};
}
</script>
</head>
<body>
1. Copy image data into clipboard or press Print Screen <br>
2. Press Ctrl+V (page/iframe must be focused):
<br /><br />
<button onclick="alert('Hello! I am an alert box!!');"></button>
<canvas style="border:1px solid grey;" id="my_canvas" width="300" height="300"></canvas>
</body>
</html>
I am using google chrome Version 70.0.3538.77
Thanks in advance
From the comments above, it sounds like you were trying to execute your bindings in the constructor of your component instead of within ngOnInit. This is a classic gotcha as the constructor spins up well before (in most cases) before the content on screen is finished rendering. ngOnInit is called as the component finalises its instantiation process.
https://angular-6ckpxd.stackblitz.io
The errors you receive are because typescript is strongly typed where javascript is not. You are pasting javascript code in (which is fine in most cases) but will need some casting to any if you want to eradicate most of them.
showMoves is a function made to show flashing for a simon game.
When the flashing lights are over I clear the interval to stop it and then I set game.playerTurn to true so I can click on colors, but game.playerTurn is changing to true as soon as showMoves is activated.
I want game.playerTurn to stay false until the showMoves function is finished showing flashing.
Here are the functions I'm using game.playerTurn in -
game.playerTurn = false;
//for flashing lights
function showMoves() {
let i = 0;
const start = setInterval(function () {
if (i >= game.computerMoves.length) {
clearInterval(start);
game.playerTurn = true;
return;
}
const move = game.computerMoves[i];
setLight(move, true);
setTimeout(setLight.bind(null, move, false), 1000); //Using bind to preset arguments
i++;
}, 2000);
}
function setLight(color, isOn) {
if (isOn) {
sounds[color.id].play();
}
color.style.backgroundColor = isOn ? colors[0].get(color) : colors[1].get(color);
}
//compareMoves is fired everytime I click on a color
function compareMoves(e) {
if (e === game.computerMoves[game.counter]) {
game.counter++;
//This is if all the moves were chosen correctly
if (game.playerMoves.length === game.computerMoves.length && e === game.computerMoves[game.computerMoves.length - 1]) {
simonHTML.displayScore.textContent = ++game.score;
game.playerTurn = false;
resetMoves();
randomMoves(++game.turn);
showMoves();
game.counter = 0;
}
} else if (game.strict) {
//if your move was wrong do this
} else {
game.playerMoves = [];
game.counter = 0;
game.playerTurn = false;
showMoves();
return false;
}
}
I'd appreciate any help with this. Here is a link to the game and all the code https://codepen.io/icewizard/pen/JLBpNQ
Where are you setting game.playerTurn back to false?
function showMoves() {
game.playerTurn = false;
let i = 0;
const start = setInterval(function() {
if (i >= game.computerMoves.length) {
clearInterval(start);
game.playerTurn = true;
return;
}
const move = game.computerMoves[i];
setLight(move, true);
setTimeout(setLight.bind(null, move, false), 1000); //Using bind to preset arguments
i++;
}, 2000);
}
Seems to work for me in the codepen example you provided
I'm creating 5 games with javascript and html5 and I'm using sound. I have a mute button that activates the function down bellow. Thing is, I want to make so that if I press the mute button and I move to another page, it will still be muted, but I can't seem to figure out how to integrate it in this function. If someone could help me out by editing the code, I'd really apreciate it :D
function init(){
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
function mute(){
if (audio.muted){
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
} else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
}
}
Modify your function like this
function init() {
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
var muteState = localStorage.getItem('muteState');
if (!muteState || muteState !== 'true') {
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
}
else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
function mute() {
if (audio.muted) {
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
} else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
localStorage.setItem('muteState', String(audio.muted));
}
}
Add the muted value to your localStorage in your 'mute' method.
function mute(){
...
audio.muted = false;
localStorage.setItem('muted', 'false');
} else {
audio.muted = true;
localStorage.setItem('muted', 'true');
}
}
}
Then on your init retrieve the localStorage value or default to false if it wasn't set prior.
function init(){
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
var isMuted = (localStorage.getItem("muted") && localStorage.getItem("muted") == 'true') || false
audio.muted = isMuted;
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
}
I digg deep into StackOwerflow but not get proper answer from any post.
First here is my code:
(function(a,n){
window.onload = function() {
var b = document.body,
userAgent = navigator.userAgent || navigator.vendor || window.opera,
playSound = function(file) {
var mediaAudio = new Audio(file);
mediaAudio.play();
};
if(b.id == 'fail' || b.id == 'success')
{
if ((/android/gi.test(userAgent) && !window.MSStream))
{
var vm = document.createElement("video"), type;
vm.autoPlay = false;
vm.controls = true;
vm.preload = 'auto';
vm.loop = false;
vm.muted = true;
vm.style.position = 'absolute';
vm.style.top = '-9999%';
vm.style.left = '-9999%';
vm.style.zIndex = '-1';
vm.id = 'video';
if(b.id == 'fail')
type = a;
else
type = n;
for(key in type)
{
if(/video/gi.test(key) && vm.canPlayType(key) == 'probably') {
vm.type = key;
vm.src = type[key];
b.appendChild(vm);
setTimeout(function(){
vm.muted = false;
vm.play();
},100);
return;
}
}
}
else
{
var au = new Audio(),type;
if(b.id == 'fail')
type = a;
else
type = n;
for(key in type)
{
if(/audio/gi.test(key) && au.canPlayType(key) == "probably") {
playSound(type[key]);
return;
}
}
}
}
}
}({
'audio/mpeg':'./sfx/not_ok.mp3',
'audio/wav':'./sfx/not_ok.wav',
'audio/ogg':'./sfx/not_ok.ogg',
'video/mp4; codecs=avc1.42E01E,mp4a.40.2':'./sfx/not_ok.mp4',
},
{
'audio/mpeg':'./sfx/ok.mp3',
'audio/wav':'./sfx/ok.wav',
'audio/ogg':'./sfx/ok.ogg',
'video/mp4; codecs=avc1.42E01E,mp4a.40.2':'./sfx/ok.mp4',
}));
I'm trying to play background sound on all devices on one special page. That page play fail or success sound.
All works great on desktop browsers but when I try to play on mobile, I not get results. In that code you see above, I add one hack where I on android platform generate hidden video and trying to autoplay but not have success.
Is there a way how I can trigger play for video or audio automaticaly?
Is there a way to emulate some click event on body to automaticaly play sound on click event or some other solution?
Thanks!
I am trying to create essentially a bot that can add a product on Foot Action to my cart. I have this code but it does not work. Can anybody debug it and just explain what I've done incorrectly. My browser is Chrome and I use TamperMonkey.
This an example of the product page:
Footaction product
window.addEventListener('load'
, function() {
var added = false;
function interval1(){
return window.setInterval(function(){
if(document.getElementById("addToCart") != null){
added = true;
window.location = "http://www.footaction.com/checkout/";
}
else if(added == false){
var cartbtn = document.getElementById("addToCartLink");
cartbtn.click();
}
}, 1000);
}
var id1 = interval1();
window.setInterval(function(){
if(added == true){
window.clearInterval(id1);
}
}, 100);
looks like you are missing the last closing squiggly bracket for window.load event
window.addEventListener('load', function() {
var added = false;
function interval1(){
return window.setInterval(function(){
if(document.getElementById("addToCart") != null){
added = true;
window.location = "http://www.footaction.com/checkout/";
}
else if(added == false){
var cartbtn = document.getElementById("addToCartLink");
cartbtn.click();
}
}, 1000);
}
var id1 = interval1();
window.setInterval(function(){
if(added == true){
window.clearInterval(id1);
}
}, 100);
}; // you were missing this line .. the ending squiggly bracket