Using onkeypress to detect up arrow being pressed (HTML and Javascript) - javascript

I've been trying to program a pingpong game without jQuery (challenge from Software Design teacher), and am planning on using onkeypress to move the paddles. However, I'm not sure how to attach a specific key to the function specified in the event handler.
It's not terribly relevant, but here's my code:
HTML:
<div id="Paddle1" class="paddle" onkeypress="PaddleMovement1(event)"></div>
<div id="Paddle2" class="paddle" onkeypress="PaddleMovement3(event)"></div>
JavaScript:
var PaddleMovement1 = function(){
document.getElementById('Paddle1Up').style.animationPlayState="running";
setTimeout(Paddle1Stop1, 25)
var Paddle1Stop1 = function(){
document.getElementById('Paddle1Up').style.animationPlayState="paused";
};
};
var PaddleMovement2 = function(){
document.getElementById('Paddle1Down').style.animationPlayState="running";
setTimeout(Paddle1Stop2, 25)
var Paddle1Stop2 = function(){
document.getElementById('Paddle1Down').style.animationPlayState="paused";
};
};
var PaddleMovement3 = function(){
document.getElementById('Paddle2Up').style.animationPlayState="running";
setTimeout(Paddle2Stop1, 25)
var Paddle2Stop1 = function(){
document.getElementById('Paddle2Up').style.animationPlayState="paused";
};
};
var PaddleMovement4 = function(){
document.getElementById('Paddle2Down').style.animationPlayState="running";
setTimeout(Paddle2Stop2, 25)
var Paddle2Stop2 = function(){
document.getElementById('Paddle2Down').style.animationPlayState="paused";
};
};
Finally, the complete thing can be found in this jsfiddle:
http://jsfiddle.net/2RfzF/2/

keypress is only fired for keypresses that result in typeable characters, not other keys. To detect other keys, use keydown and keyup. This should be fairly clear from the specification:
A user agent must dispatch this event when a key is pressed down, if and only if that key normally produces a character value.
This page is a handy guide to the madness that is keyboard events in JavaScript across browsers...
Separately, for your purposes I'd probably trap the events on document rather than on a specific element (keydown and keyup bubble, so that works).
For example:
(function() {
if (document.addEventListener) {
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keydown", keyUpHandler, false);
}
else if (document.attachEvent) {
document.attachEvent("onkeydown", function() {
keyDownHandler(window.event);
});
document.attachEvent("onkeydown", function() {
keyUpHandler(window.event);
});
}
else {
// If you want to support TRULY antiquated browsers
document.onkeydown = function(event) {
keyDownHandler(event || window.event);
};
document.onkeyup = function(event) {
keyUpHandler(event || window.event);
};
}
function keyDownHandler(e) {
var key = e.which || e.keyCode;
display("keydown: " + key);
}
function keyDownHandler(e) {
var key = e.which || e.keyCode;
display("keyup: " + key);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
Live Copy | Source

Related

Using backpressure for keystroke in RxJs

I'm trying to capture the user keystroke using RxJS, and for each stroke, generate a result object which contains the key, the duration of the stroke (time between keyup and keydown events), and the interval between previous strokes (using timeInterval).
See the image bellow for an overview.
So far, my code is working : Hello outputs ShiftLeftHELLO.
But when I writing faster (as usual I mean), everything breaks up and World outputs ShiftLeftShiftLeftOLD.
Do you have any suggestion on implementing backpressure, buffering or something else in my code to prevent this behavior ?
(function (document) {
var textarea = document.querySelector("#input");
var keyUpStream = Rx.DOM.keyup(textarea);
var keyDownStream = Rx.DOM.keydown(textarea);
var keyStrokeStream = Rx.Observable.merge(keyDownStream, keyUpStream);
var keystroke = keyStrokeStream.filter((function() {
var keysPressed = {};
return function(e) {
var k = e.which;
if (e.type == 'keyup') {
delete keysPressed[k];
return true;
} else if (e.type == 'keydown') {
if (keysPressed[k]) {
return false;
} else {
keysPressed[k] = true;
return true;
}
}
};
})())
.distinctUntilChanged(function (e){
return e.type + e.which;
})
.timeInterval()
.bufferWithCount(2)
.zip(function (evts){
return {
"ts" : Date.now(),
"key": evts[0].value.code,
"evts" : evts,
"duration" : evts.reduce(function(a, b){
return b.value.timeStamp - a.value.timeStamp;
})
};
}).subscribe(function (e){
console.log(e);
document.querySelector("#output").textContent += e.key.replace("Key", '');
document.querySelector("#console").textContent += JSON.stringify(e);
});
})(document);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs-dom/7.0.3/rx.dom.js"></script>
<h1>KeyStroke</h1>
<textarea id="input" rows="5" cols="50"></textarea>
<div id="output"></div>
<div id="console"></div>
Disclaimer: Rxjs noob here.
The problem is that your code expect a keyup from a key after a keydown from that same key. When you type fast, you have a race condition on keystrokes, resulting in a buffer with several keydowns or keyups. Not what you expect in your buffer.
I've modified the code to take advantage of your filter function. That function returns only keyup events and it saves the corresponding keydown stroke. This way, you calculate the interval within the filter function. I'm pretty sure that there's a more elegant solution using only RxJS functions but since you already used state in the filter function, I've modified it a little.
The snippet now shows a proper output. I think it solves your problem but it's not a good way of using RxJS (as I said we're storing state in the filter function).
(function (document) {
var textarea = document.querySelector("#input");
var keyUpStream = Rx.DOM.keyup(textarea);
var keyDownStream = Rx.DOM.keydown(textarea);
var keyStrokeStream = Rx.Observable.merge(keyDownStream, keyUpStream);
var keystroke = keyStrokeStream.filter((function() {
var keysPressed = {};
return function(e) {
var key = e.which;
var result;
if (e.type == 'keyup' && keysPressed.hasOwnProperty(key)) {
e.strokeInterval = Date.now() - keysPressed[key];
delete keysPressed[key];
return true;
} else if (e.type == 'keydown') {
if (!keysPressed.hasOwnProperty(key)) {
keysPressed[key] = Date.now();
}
return false;
}
return false;
};
})())
.map(function (evt){
return {
"ts" : Date.now(),
"key": evt.code,
"duration" : evt.strokeInterval
};
})
.subscribe(function (e){
console.log(e);
document.querySelector("#output").textContent += e.key.replace("Key", '');
document.querySelector("#console").textContent += JSON.stringify(e);
});
})(document);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs-dom/7.0.3/rx.dom.js"></script>
<h1>KeyStroke</h1>
<textarea id="input" rows="5" cols="50"></textarea>
<div id="output"></div>
<div id="console"></div>

Is there a way to combine 2 or more events that do similar operations to use the DRY principle

I have two events one is a key press and the other is a click event. the events do similar thing but they are different(ex: they search for different elements and in my real code they call diff functions depending on which button and which input box was entered) . should i combine the events? if so how?
$(document).ready( function(){
function replaceQ(){
var num1 = Math.floor(Math.random() *10)
var num2 = Math.floor(Math.random() *10)
$(".container").children().remove()
$(".container").append("<div>" + num1 + " </div><div>" + num2 +"</div>")
.append("<input class='input'>").append("<button class = 'button'>Go</button>")
var result = num1 + num2;
return [result]
}
var outResult = replaceQ()[0]
$(".container").on("click", "button", function(){
var entry = $(this).siblings(".input").val()
if(outResult == entry){
outResult = replaceQ()[0]
}
})
$(".container").on("keypress", "input", function(e){
var entry = $(".input").val()
if(outResult == entry && e.which == 13){
outResult = replaceQ()[0]
}
})
var processAnswer = function processAnswer(e){
//if(e.target.className === "input")
}
$(".input, .button").on("click", processAnswer)
});
you can get Event.type in callback function, see below sample code
var processAnswer = function processAnswer(e){
if(e.type == 'click'){
//code here
}
else if(e.type == 'keypress'){
//code here
}
}
$(".input, .button").on("click keypress", processAnswer)
Yes - there is. You can use the bind method as follows:
$(".container button").bind("click keypress", function(){
....
});
edit
You can check wether the button or the container was triggered as follows
$(".container button, .container input").bind("click keypress", function(event){
var target = $(event.target);
if(target.is('button'))
{
alert("button");
}
else if(target.is('input'))
{
alert("input");
}
});
See this fiddle for example.
The event listeners themselves are separate enough that it would probably make more sense to just make a single function for the handler. So part of your code would look like this:
//New Event Handling function
function eventHandler(e) {
var entry = $(".input").val()
if(outResult == entry && (!e.which || e.which == 13)){
outResult = replaceQ()[0]
}
}
$(".container").on("click", "button", eventHandler);
$(".container").on("keypress", "input", eventHandler);
I don't think it makes sense to combine the event listeners as they are listening to specific elements and combining them (like $(".container").on("click keypress", eventHandler);) could get weird as it would trigger when you click on a text field. So for that reason, I'd focus on combining the handler like above.

can not find the solution to my "addEventListener" function

I am stuck on problem where I try to utilies the addEventListener.
I did try to find solutions on the web but I think my knowledge is to limited to pick the suitable answer.
What I tried is to invoke a function "addFile()" when a key is pressed in this example enter(13) unfortunatly nothing happens. I could add the onkeypress attribute to the input "add-file" with a slightly edited addFileOnKeyEvent(event) but I'm trying to understand what is wrong with my eventListener.
I hope you could follow my explanation, as this is my first question. :)
function addFile() {
var x = document.getElementById("add-file").value;
x = x + ".xml";
var lbl = document.createElement("label");
var node = document.createTextNode(x);
lbl.appendChild(node);
var element = document.getElementById("appendable");
element.appendChild(lbl);
}
function addFileOnKeyEvent(event) {
var evt = event.keyCode;
var textField = document.getElementById("add-file").addEventListener("keypress", function() {
if (evt == 13) {
addFile();
}
});
}
<label>Dateien</label>
<input id="add-file" type="text" onclick="this.select();">
<button type="submit" onclick="addFile()">Hinzufügen</button>
<div class="data-display">
<span id="appendable"></span>
</div>
At first, addFileOnKeyEvent() is never called before anywhere. So you must call it when you try to add file. Or you must bind the event to the text field by default.
Also need not pass event object to addFileOnKeyEvent(). The event must be captured in the addEventListener callback function.
function addFile() {
var x = document.getElementById("add-file").value;
x = x + ".xml";
var lbl = document.createElement("label");
var node = document.createTextNode(x);
lbl.appendChild(node);
var element = document.getElementById("appendable");
element.appendChild(lbl);
}
function addFileOnKeyEvent() {
document.getElementById("add-file").addEventListener("keypress", function(event) {
var evt = event.keyCode;
if (evt == 13) {
addFile();
}
});
}
// call the function here
addFileOnKeyEvent();
// else just put the event handler part alone. The function is unnecessary here.
<label>Dateien</label>
<input id="add-file" type="text" onclick="this.select();">
<button type="submit" onclick="addFile()">Hinzufügen</button>
<div class="data-display">
<span id="appendable"></span>
</div>
That's not how events work. Try this...
document.getElementById("add-file").addEventListener(
"keypress",
function(event) {
if (event.keyCode == 13) {
addFile();
}
});
Instead of...
function addFileOnKeyEvent(event) {
var evt = event.keyCode;
var textField = document.getElementById("add-file").addEventListener("keypress", function() {
if (evt == 13) {
addFile();
}
});
}

Temporarily disable all currently active jQuery event handlers

I am making a TD element of table editable on double click:
$(document).on("dblclick", "#table>tbody>tr>td.cell", function(e) {
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function() {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
});
function stub(e) {
e.stopImmediatePropagation();
return false;
}
But when i double click on the text inside the editable div, the double click event propagates to the parent td causing undesired consequences. There are also other events (select, mousedown, etc) i want to prevent, so writing a stub for each of them doesn't look nice to me.
Is there a way to disable all currently active jQuery event handlers and enable them afterwards? Or somewhow stop propagating all events from the editable div to its parents?
Or somewhow stop propagating all events from the editable div to its parents?
It may not be very palatable, but it's not that bad to specifically disable the events:
$(this).on("select mousedown mouseup dblclick etc", false);
(Assuming this refers to the cell you're editing.)
There is a limited number of events, after all, and on allows you to list them in a space-delimited string and disable them by passing false.
You can then re-enable them by passing the same list and false again into off.
Use on / off JQuery methods :
var myFunction = function(e) {
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function() {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
};
function stub(e) {
e.stopImmediatePropagation();
return false;
}
//Active the events
$(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction);
//Disable the events
$(document).off("dblclick", "#table>tbody>tr>td.cell",myFunction);
//Reactive the events
$(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction);
Update
You can also manage a variable set to true if the event must not be taking into account :
var skipEvent = true;
$(document).on("dblclick", "#table>tbody>tr>td.cell", function (e) {
//Check variable and skip if true
if (skipEvent)
return false;
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function () {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
});

Trying to implement Google's Fast Button

I'm trying to implement Google's Fast button for the mobile touch events, and I seem to be stuck. I'm trying to set it up so that I can make links into fastbuttons, but I can't seem to get my library structure right. What ends up happening is the fastbutton re-inits itself when I try to run a for loop on the links.
I'm sure it's just the way I'm setting up the library. Can someone please check it out?
http://code.google.com/mobile/articles/fast_buttons.html
;(function() {
/*Construct the FastButton with a reference to the element and click handler.*/
this.FastButton = function(element, handler) {
console.log('fastbutton init');
this.element = element;
this.handler = handler;
console.log(this);
element.addEventListener('touchstart', this, false);
element.addEventListener('click', this, false);
};
/*acts as an event dispatcher*/
this.FastButton.prototype.handleEvent = function(event) {
console.log(event);
switch (event.type) {
case 'touchstart': this.onTouchStart(event); break;
case 'touchmove': this.onTouchMove(event); break;
case 'touchend': this.onClick(event); break;
case 'click': this.onClick(event); break;
}
};
/*Save a reference to the touchstart coordinate and start listening to touchmove and
touchend events. Calling stopPropagation guarantees that other behaviors don’t get a
chance to handle the same click event. This is executed at the beginning of touch.*/
this.FastButton.prototype.onTouchStart = function(event) {
event.stopPropagation();
this.element.addEventListener('touchend', this, false);
document.body.addEventListener('touchmove', this, false);
this.startX = event.touches[0].clientX;
this.startY = event.touches[0].clientY;
};
/*When /if touchmove event is invoked, check if the user has dragged past the threshold of 10px.*/
this.FastButton.prototype.onTouchMove = function(event) {
if (Math.abs(event.touches[0].clientX - this.startX) > 10 ||
Math.abs(event.touches[0].clientY - this.startY) > 10) {
this.reset(); //if he did, then cancel the touch event
}
};
/*Invoke the actual click handler and prevent ghost clicks if this was a touchend event.*/
this.FastButton.prototype.onClick = function(event) {
event.stopPropagation();
this.reset();
this.handler(event);
if (event.type == 'touchend') {
console.log('touchend');
//clickbuster.preventGhostClick(this.startX, this.startY);
}
};
this.FastButton.prototype.reset = function() {
this.element.removeEventListener('touchend', this, false);
document.body.removeEventListener('touchmove', this, false);
};
this.clickbuster = function() {
console.log('init clickbuster');
}
/*Call preventGhostClick to bust all click events that happen within 25px of
the provided x, y coordinates in the next 2.5s.*/
this.clickbuster.preventGhostClick = function(x, y) {
clickbuster.coordinates.push(x, y);
window.setTimeout(this.clickbuster.pop, 2500);
};
this.clickbuster.pop = function() {
this.clickbuster.coordinates.splice(0, 2);
};
/*If we catch a click event inside the given radius and time threshold then we call
stopPropagation and preventDefault. Calling preventDefault will stop links
from being activated.*/
this.clickbuster.onClick = function(event) {
for (var i = 0; i < clickbuster.coordinates.length; i += 2) {
console.log(this);
var x = clickbuster.coordinates[i];
var y = clickbuster.coordinates[i + 1];
if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) {
event.stopPropagation();
event.preventDefault();
}
}
};
})(this);
document.addEventListener('click', clickbuster.onClick, true);
clickbuster.coordinates = [];
Try calling the constructor with new?
new FastButton(el, function() {});

Categories

Resources