I'm making my own player with drumpad and i need help to assign functions to keyboard keys. I've got playlist with (now) 3 sounds:
var playlist = [
{
artist: "Snare",
title: "Snare",
source: "Snare.wav"
},
{
artist: "Kick",
title: "Kick",
source: "Kick.wav"
},
{
artist: "Clap",
title: "Clap",
source: "Clap.wav"
},
];
I've got some functions which i'm running by buttons:
var currentSong = 0;
var play = function() {
var audio = document.getElementById("audio1");
audio.play();
}
var pause = function() {
var audio = document.getElementById("audio1");
audio.pause();
}
var jeden = function() {
var audio = document.getElementById("audio1");
currentSong = 0;
audio.src = playlist[currentSong].source;
}
var dwa = function() {
var audio = document.getElementById("audio1");
currentSong = 1;
audio.src = playlist[currentSong].source;
}
var trzy = function() {
var audio = document.getElementById("audio1");
currentSong = 2;
audio.src = playlist[currentSong].source;
}
And the html:
<body>
<audio autoplay="autoplay" ontimeupdate="showinfo()" id="audio1"
controls="controls"></audio>
<br/>
<button onclick="jeden()">1</button>
<button onclick="dwa()">2</button>
<button onclick="trzy()">3</button>
</body>
I think the essiest way is to assign buttons to keyboard keys. Anybody can help me?
dzieĆ dobry
The code will be something like this. You can change keypress() to keyup() or keydown() if suitable - check the documentation of those functions to appreciate the differences.
$('body').keypress(function( event ) {
if ( event.which == 49 ) {
jeden();
}
});
I referred to this page to determine the number 49 means key 1:
https://css-tricks.com/snippets/javascript/javascript-keycodes/
I should mention this is a jQuery solution and you will need to learn some basic jQuery setup. It is a popular approach to solving this problem. You will also be able to use jQuery to do your existing stuff a much nicer way.
Here is an example. https://jsfiddle.net/7j0krzx5/
use this
$(document ).on( "keydown", function(event) {
if (event.which === 80) // P key
{
event.preventDefault();
// do something e.g
}
else if (event.which === 78) // N key
{
event.preventDefault();
// do something
}
// console.log(event.which);
});
JSFiddle example
If you don't want to use jquery
var play = function() {
alert("Play");
}
var next = function() {
alert("Next");
}
function keyDownListener(event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(keyCode === 80){ // P key
event.preventDefault();
play()
}
else if (keyCode == 78 ) { // N key
event.preventDefault();
next();
}
}
document.addEventListener("keydown", keyDownListener, false);
JSFiddle example
Related
I've been trying to make a website for people that feel their life is in danger or anything like that. I'm trying to recreate the Trevor Project's escape key function with javascript.
I have some base code but it's not working:
window.addEventListener("keydown", checkKeyPressed, false);
var escTime = 0;
function checkKeyPressed(evt) {
if (evt.keyCode === "27") {
window.clearTimeout();
escTime++;
window.setTimeout(function(){
escTime = 0;
}, 1000);
}
if (escTime == 3) {
window.location.replace("https://classroom.google.com/h");
escTime = 0;
}
}
I'd say you're fairly close, but:
You have to remember the handle from setTimeout in order to cancel it, because you have to give it to clearTimeout.
keyCode is deprecated (though unlikely to actually go away), look at key and code instead.
There's no point in assigning 0 back to escTime, the treplace` leaves the page anyway.
So perhaps:
window.addEventListener("keydown", checkKeyPressed, false);
let escapeTimerHandle = 0;
let escapeCount = 0;
function checkKeyPressed(evt) {
if (evt.key === "Escape" || evt.key === "Esc") {
clearTimeout(escapeTimerHandle);
escapeCount++;
if (escapeCount == 3) {
window.location.replace("https://classroom.google.com/h");
} else {
escapeTimerHandle = setTimeout(function(){
escapeCount = 0;
}, 1000);
}
}
}
You can accomplish this using a closure:
function createCheckKeyPressFunction()
{
let timeout;
let escTime = 0;
function checkKeyPressed(evt)
{
if (evt.key === "Escape")
{
console.log("Escape Detected");
window.clearTimeout(timeout);
escTime += 1;
timeout = window.setTimeout(()=>
{
escTime = 0;
console.log("Escape count reset to zero, due to timeout.");
}, 1000);
}
if (escTime === 3) {
let url = "https://classroom.google.com/h";
console.log(url);
window.location.replace(url);
escTime = 0;
}
}
return checkKeyPressed;
}
let checkKeyPressed = createCheckKeyPressFunction();
window.addEventListener("keydown", checkKeyPressed, false);
<p>Click to give this embedded snippet focus, and then test by hitting the ESC key.</p>
Since the code snippet (above) is embedded in this page, be sure to click into it after running it (to give it focus) before testing it with the Esc key.
I want to know how to stop an audio that is set to "autoplay" using the X key on the keyboard. I have tried in a couple of method but it doesn't work.
That's my code:
JavaScript:
var source = "audio/homepage_benvenuto.mp3";
var audio = document.createElement("audio");
audio.autoplay = true;
audio.load()
audio.addEventListener("load", function()
{
audio.play();
}, true);
audio.src = source;
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e)
{
if (e.keyCode == "88") // 88 = X: interrompe audio in corso
{
player.pause();
player.currentTime = 0;
document.getElementById('audioA').pause();
}
}
In this fiddle I made a script building a play button for audio files, that allows playing the file only twice and then disables it. But after reloading the page, the button is active again. How can I make sure, the button stays disabled for a defined duration of 30 seconds for example?
I was wrapping my head around localStorage and found a promising question/answer here, but couldn't transfer the knowhow to my usecase. Can someone help me out?
function buildLimitedPlay(selector) {
$(selector).each(function(i) {
var myaudio = $(this)[0];
var button = $(this).next("input.limited-play")[0];
var index = 2;
$(button).css('display', 'block');
$(button).val("Play Clip");
$(myaudio).on('ended', function() {
index--;
$(button).val('Play again');
if (index == 0) {
$(button).css('background', 'red');
$(button).css('cursor', 'not-allowed');
$(button).css('text-decoration', 'line-through');
$(button).disabled;
}
});
$(button).on("click", function() {
if (index > 0) {
myaudio.play();
}
});
});
}
buildLimitedPlay("audio.limited-play");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<audio class="limited-play" preload="none">
<source src="http://www.noiseaddicts.com/samples_1w72b820/3726.mp3" type="audio/mpeg">
</audio>
<input value="Play Clip" class="limited-play" type="button">
I'm assuming you want to automatically enable the play button after the predefined disabled time passes, also you will have multiple audios to play with multiple buttons. here is the code that will work after refresh and automatically enable the button after time out.
$(function () {
function now() { return +new Date }
var db = window.db = {
get: function (key) {
var entry = JSON.parse(localStorage.getItem(key) || "0");
if (!entry) return null;
if (entry.ttl && entry.ttl + entry.now < now()) {
localStorage.removeItem(key);
return null;
}
return entry.value;
},
set: function (key, value, ttl) {
localStorage.setItem(key, JSON.stringify({
ttl: ttl || 0,
now: now(),
value: value
}));
}
};
function buildLimitedPlay(selector) {
$(selector).each(function (i) {
var getRemainingTurn = function () {
var turn = db.get('remainingTurn' + i);
return null == turn ? 2 : turn;
};
var setRemainingTurn = function (turn, timeToLiveInMillisecond) {
db.set('remainingTurn' + i, turn, timeToLiveInMillisecond || 0);
};
var myaudio = this;
var $button = $(this).next("input.limited-play:first");
$button.css('display', 'block')
.on("click", function () {
if (getRemainingTurn() > 0) {
myaudio.play();
}
});
var setAudioState = function (turn) {
$button.val(2 == turn ? 'Play Clip' : 'Play again');
if (turn == 0) {
$button.css({ 'background': 'red', 'cursor': 'not-allowed', 'text-decoration': 'line-through' });
}
else {
$button.css({ 'background': '', 'cursor': '', 'text-decoration': 'none' });
}
};
var disabledPeriodInMillisecond = 30 * 1000;
var tryEnableAudio = function () {
turn = getRemainingTurn();
if (0 == turn) {
//because we don't know how much time passed since it was disabled in case of a page refresh for simplicity.
setTimeout(tryEnableAudio, 50);
return;
}
setAudioState(turn);
};
$(myaudio).on('ended', function () {
var turn = getRemainingTurn();
turn--;
setAudioState(turn);
if (0 == turn) {
setRemainingTurn(turn, disabledPeriodInMillisecond);
tryEnableAudio();
}
else {
setRemainingTurn(turn);
}
});
setAudioState(getRemainingTurn());
tryEnableAudio();
});
}
buildLimitedPlay("audio.limited-play");
});
So I'm trying to be able to trigger a script using a combinations of keypresses.
var down = {
};
$(document).chardown(function (e) {
down[e.charCode] = true;
}).charup(function (e) {
if (down[68] && down[69] && down[86]) {
var nextButton = document.getElementsByClassName('button-next') [0];
nextButton.click();
}
down[e.keyCode] = false;
});
This is the code I've got so far. So the intention is (afaik) to trigger the
var nextButton = document.getElementsByClassName('button-next') [0];
nextButton.click();
When I press e+d+v. But it isn't working. And if I only use the above part it keeps changing episode (Obvioulsy).
I didn't find any documentation related to chardown and charup in jquery or greasemonkey.I think you were trying to use keydown and keup. You should replace charCode with keyCode.
var down = {};
$(document).keydown(function (e) {
down[e.keyCode] = true;
}).keyup(function (e) {
if (down[68] && down[69] && down[86]) {
alert("Hello");
}
down[e.keyCode] = false;
});
I have a textbox has a numeric value.
now what I want is to keep increasing that numeric value while im pressing and holding any of arrow keys.
I know how to do this if I was pressing only one time. it will be increased by 1 only. but what If I want to keep increasing the value while i'm holding the arrow keys. how to do that?
thanks
There's a small jQuery plugin for doing this:
https://github.com/nakupanda/number-updown
Usages:
$('#simplest').updown();
$('#step').updown({
step: 10,
shiftStep: 100
});
$('#minMax').updown({
min: -10,
max: 10
});
$('#minMaxCircle').updown({
min: -10,
max: 10,
circle: true
});
View live demo here:
http://jsfiddle.net/XCtaH/embedded/result/
Keyboard and mousewheel events supporte
This is not fully tried and tested by me, but here is a thought - You might want to track KeyDown events because that's the event which is queued by the OS when the key is first pressed. You might also want to implement some sort of delay when incrementing this way so as not to overwhelm the client-side script and have numbers change at a speed to high for user to track.
ok after some tests I made here is how its done:
var setTimeoutId;
var keyIs = "up";
function myIncrementFunction()
{
var num = parseFloat(myText.value)+1;
myText.value = num;
}
myText.onkeydown = function(e)
{
keyIs = "down";
if(keyIs == "down")
{
var e = e || event ;
if (e.keyCode == 38)
{
for(var s=0; s<1; s++)
setTimeoutId = setTimeout('myIncrementFunction()',100);
}
}
}
myText.onkeyup = function(e)
{
keyIs = "up";
}
If you don't care about supporting Opera, this is easy:
textbox.onkeydown = function(e)
{
if (e.keyCode == 38)
{
incrementTextBox();
}
}
However, Opera doesn't fire keydown for key repeats... you'll have to mimic that by calling incrementTextBox() at an interval, and stopping when the key is lifted. I tested this in WebKit (Chrome 6.0), FF3, Opera 10.6, IE7, IE8, IE9, even IE Quirks:
var textbox = null;
window.onload = function()
{
var timeoutId = null;
var intervalId = null;
var incrementRepeatStarted = false;
function startIncrementKeyRepeat()
{
timeoutId = window.setTimeout(function()
{
intervalId = window.setInterval(incrementTextBox, 50);
}, 300);
}
function abortIncrementKeyRepeat()
{
window.clearTimeout(timeoutId);
window.clearInterval(intervalId);
timeoutId = null;
intervalId = null;
}
function endIncrementKeyRepeat()
{
abortIncrementKeyRepeat();
incrementRepeatStarted = false;
}
textbox = document.getElementById("incrementer");
textbox.onkeydown = function(e)
{
e = e || window.event;
if (e.keyCode == 38)
{
if (!incrementRepeatStarted)
{
startIncrementKeyRepeat();
incrementRepeatStarted = true;
}
else if (timeoutId || intervalId)
{
abortIncrementKeyRepeat();
}
incrementTextBox();
}
else if (incrementRepeatStarted)
{
endIncrementKeyRepeat();
}
}
textbox.onkeyup = endIncrementKeyRepeat;
}
function incrementTextBox()
{
var val = parseInt(textbox.value) || 0;
val++;
textbox.value = val;
}
I wanted to do this, i just used input field with type="number"