Javascript keydown function is only being called once - javascript

For some reason when I call this function it only works on the first keydown. Im not sure what I'm doing wrong.
$(document).ready(function(){
$(document).keydown(function(e) {
var x = 10;
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 40){
function rise(x){
$('#div2').css('bottom',x+'%');
}
rise(x);
x++;
}

You don't see it working because you reinitialize x to 10 every time.
A solution is to put x in the external scope :
$(document).ready(function(){
var x = 10;
$(document).keydown(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
function rise(x){
$('#div2').css('bottom',x+'%');
}
rise(x);
x++;
});
});
Note that there's no reason to define a rise function here. You could simply do
$(document).ready(function(){
var x = 10;
$(document).keydown(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
$('#div2').css('bottom',x+'%');
x++;
});
});
(I hope there's a reason for the code part).

Related

Javascript event is not triggering

I am trying to do the trigger keyDown event on click of a button, but this is not working.
$("#button").click(function() {
var e = jQuery.Event("keydown");
e.keyCode = 37;
$(this).trigger(e);
return false;
});
But the event is not triggering. Can anyone suggest please?
It looks to me like it's working.
Try the snippet below with the test function:
$(document).ready(function() {
$("#button").click(function() {
var e = jQuery.Event("keydown");
e.keyCode = 37;
$(this).trigger(e);
console.log(e);
return false;
});
});
// test trigger
$(window).keydown(function(e) {
key = e.keyCode ? e.keyCode : e.which;
if (key === 37) {
alert(`Left arrow triggered, (keyCode ${key})`);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Trigger key 37 (left arrow)</button>

How to call object oriented javascript function from html

I want call below code from HTML on event (right arrow key).
var Anim = function() {
var box = document.getElementById("square");
};
Anim.prototype.Start = function(event){
if(event.keyCode == 39){
box.style.left = (box.offsetLeft + 100)+"px";
}
};
Anim.prototype.Stop = function(event){
if(event.keyCode == 37){
box.style.left = (box.offsetLeft)+"px";
}
};
var Myanim = new Anim();
Here is my HTML
<div id="square" style="position: absolute;">This is my box</div>
Using jQuery :
$(document).keypress(function(event) {
alert('Handler for .keypress() called. - ' + event.charCode);
});
To import jquery in your project :
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
If you want to use Javascript only :
window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 37) { //left key
alert('up');
} else if (code === 40) { //down key
alert('down');
}};

JavaScript How to allow only one symbol at the begining of string

I would like to allow the users to put only one kind of symbol (character) in input and only at the beginning of string.
Of course on keyDown/keyUp event. I'm looking-for the fastest solution.
Supposing you have an input like
<input type="text" id="text">
you can use the following code
$(function(){
var alreadyIn = 0;
var chars = [33, 64, 35]; // Place here the codes for accepted chars (!##$ etc)
$("#text").on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(chars.indexOf(code) != -1) {
if($(this).caret() != 0){return false;}
if(alreadyIn){return false;}
alreadyIn++
} else {
if(alreadyIn && $(this).caret() == 0){return false;}
}
return true;
}).on('keyup', function(e){ // Keyup event to catch backspace and delete
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 8 || code == 46) {
var current = $(this).val();
var instances = 0;
chars.forEach(function(char) {
if(current.search(String.fromCharCode(char)) > -1){instances++;}
});
alreadyIn = instances == 0 ? 0 : 1;
}
}).bind("cut copy paste", function(e) { // Do not allow cut copy paste in field
e.preventDefault();
});
});
EDIT
I've updated the answer. You have to include jquery caret plugin also. You can find it here

Javascript/jQuery: Convert key combo to string?

I'm looking for an existing Javascript library, or even better, a jQuery plugin, which detects a key combo and outputs the corresponding string (for example, "ctrl+shift+f"). This is to allow a user to configure a key combo for a Google Chrome plugin. The preferences behavior for BetterTouchTool ( http://www.boastr.de/ ) is a good example of what I'm talking about. Has anyone come across something like this?
I think something of this kind might help:
document.onkeydown = KeyDownHandler;
document.onkeyup = KeyUpHandler;
var CTRL = false;
var SHIFT = false;
var ALT = false;
var CHAR_CODE = -1;
function KeyDownHandler(e) {
var x = '';
if (document.all) {
var evnt = window.event;
x = evnt.keyCode;
}
else {
x = e.keyCode;
}
DetectKeys(x, true);
DoSometing();
}
function KeyUpHandler(e) {
var x = '';
if (document.all) {
var evnt = window.event;
x = evnt.keyCode;
}
else {
x = e.keyCode;
}
DetectKeys(x, false);
DoSometing();
}
function DetectKeys(KeyCode, IsKeyDown) {
if (KeyCode == '16') {
SHIFT = IsKeyDown;
}
else if (KeyCode == '17') {
CTRL = IsKeyDown;
}
else if (KeyCode == '18') {
ALT = IsKeyDown;
}
else {
if(IsKeyDown)
CHAR_CODE = KeyCode;
else
CHAR_CODE = -1;
}
}
function DoSometing() {
//check for keys here
}
I hope it'll be useful
$(document).keypress(function(e) {
alert(
(e.ctrlKey ? 'ctrl+' : '') +
(e.altKey ? 'alt+' : '') +
(e.shiftKey ? 'shift+' : '') +
String.fromCharCode(e.which).toLowerCase()
);
});
This will register the keys; not sure how you're going to block the ctrl/alt keys from getting interpreted though.
browser support: http://www.quirksmode.org/js/keys.html
I forgot I even asked this question! After many months, I've written a plugin myself that does exactly this =)
http://suan.github.com/jquery-keycombinator/

Javascript on second keypress

I've been wondering if there was a simple way to detect if a user presses the same character on the keyboard twice within one second. I've written some code that kind of works but it's unreliable.
var escapeCount = 0;
function reset() {
escapeCount = 0;
setTimeout('reset();', 1000);
}
window.onload = function() {
reset();
};
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (code == 27) escapeCount +=1;
if (escapeCount == 2) {
// stuff on second escape
}
};
Is there a better way to do this? Thanks
It would make sense to reset after 1 second has passed since the last character was pressed. Example:
var lastChar = -1;
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (lastChar == code) {
// Same key was pressed twice in a row within 1 second.
} else {
lastChar = code;
setTimeout(function() {lastChar = -1;}, 1000);
}
};
Your timer resets every second, so you not only have to press Escape again within a second of the last Escape, but that also has to have no timeout in between the presses.
It's probably easier to forget the timeout and just remember the time of the last keypress instead:
var lastescapetime= null;
document.onkeyup= function(event) {
if (event===undefined) event= window.event;
if (event.keyCode===27) {
var now= new Date().getTime();
if (lastescapetime!==null && now<lastescapetime+1000) {
alert('You double-escaped!');
lastescapetime= null;
} else {
lastescapetime= now;
}
} else {
lastescapetime= null;
}
};

Categories

Resources