How to call object oriented javascript function from html - javascript

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');
}};

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>

I want a right arrow to change variable, but it will not work

When I hit the right arrow, it does not change the variable. Here's my code:
var squareX = 10;
document.addEventListener("keypress", function(e) {
if (e.keyCode === 39) {
squareX += 10;
}
});
Use keydown instead of keypress:
document.addEventListener("keydown", function(e) {
if (e.keyCode === 39) {
squareX += 10;
}
});
That did the trick for me!

How to write a good Caps Lock detection solution in JavaScript?

Found this Caps Lock detection solution. Fiddle here: https://jsfiddle.net/07ugkacn/11/ (Thank you Armfoot). JS/jQuery code here:
$(function () {
var isShiftPressed = false;
var isCapsOn = null;
$("#txtName").bind("keydown", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 16) {
isShiftPressed = true;
}
});
$("#txtName").bind("keyup", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 16) {
isShiftPressed = false;
}
if (keyCode == 20) {
if (isCapsOn == true) {
isCapsOn = false;
$("#error").hide();
} else if (isCapsOn == false) {
isCapsOn = true;
$("#error").show();
}
}
});
$("#txtName").bind("keypress", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode >= 65 && keyCode <= 90 && !isShiftPressed) {
isCapsOn = true;
$("#error").show();
} else {
$("#error").hide();
}
});
});
Works perfectly for my needs. I'm trying to rewrite it in JavaScript though, with no jQuery. How do I rewrite the bind methods without the jQuery? I've tried storing the input fields in a variable and writing
passwordInput.onkeyup = function(e) { ... }
... For example. But to no avail. Think this is what's stopping this solution from working.
Help pls thx.
EDIT: Figured it out on my own
For whom it may concern, a solution for caps detection in vanilla JavaScript. The problem with most of the solutions floating around on the internet is they only show/hide an alert/popup when the user starts typing in the input field. This is not optimal because the "Caps Lock is on" notification is still visible after the user has turned Caps Lock off, and remains so until they resume typing. This is long and unwieldy, and I still don't quite understand it myself. But I recommend it all the same.
function capsDetect() {
var body = document.getElementsByTagName('body')[0];
var isShiftPressed = false;
var isCapsOn = null;
var capsWarning = document.getElementById('caps-lock-warning');
body.addEventListener('keydown', function(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode = 16){
isShiftPressed = true;
}
});
body.addEventListener('keyup', function(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if(keyCode == 16) {
isShiftPressed = false;
}
if(keyCode == 20) {
if(isCapsOn == true) {
isCapsOn = false;
capsWarning.style.visibility = 'hidden';
} else if (isCapsOn == false) {
isCapsOn = true;
capsWarning.style.visibility = 'visible';
}
}
});
body.addEventListener('keypress', function(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if(keyCode >= 65 && keyCode <= 90 && !isShiftPressed) {
isCapsOn = true;
capsWarning.style.visibility = 'visible';
} else {
capsWarning.style.visibility = 'hidden';
}
});
}
shiftCaps();
Gaweyne, nicely done! I tested your pure JS code and there are some things that I modified which you may find interesting:
ignored control characters while typing (<= 40), such as directional and removal keys;
replaced if (keyCode = 16){ to if (keyCode === 16){ and other == in the same way;
used display property instead of visibility (CSS);
considered isCapsOn as a boolean, always;
called capsDetected instead of shiftCaps.
You can run the snippet below to check it out:
function capsDetect() {
var body = document.getElementsByTagName('body')[0];
var isShiftPressed = false;
var isCapsOn = false;
var capsWarning = document.getElementById('error');
body.addEventListener('keydown', function(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode === 16) {
isShiftPressed = true;
}
});
body.addEventListener('keyup', function(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode === 16) {
isShiftPressed = false;
}
if (keyCode === 20) {
if (isCapsOn) {
isCapsOn = false;
capsWarning.style.display = 'none';
} else {
isCapsOn = true;
capsWarning.style.display = 'inline-block';
}
}
});
body.addEventListener('keypress', function(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode <= 40)
return;
if (keyCode >= 65 && keyCode <= 90 && !isShiftPressed) {
isCapsOn = true;
capsWarning.style.display = 'inline-block';
} else {
capsWarning.style.display = 'none';
}
});
}
capsDetect();
body {
font-family: Arial;
font-size: 10pt;
}
#error {
border: 1px solid #FFFF66;
background-color: #FFFFCC;
display: inline-block;
margin-left: 10px;
padding: 3px;
display: none;
}
<form action="">
<input id="txtName" type="text" /><span id="error">Caps Lock is ON.</span>
</form>
Maybe some more tweaking will make it perfect... There is still the CAPS LOCK detection on page load: maybe by simulating user input in the background will let us know, but right now I haven't completely figured it out yet.
Btw, I never thought of doing this before, but it is clear that it helps users, specially in passwords fields. In fact, I may personally use it! So I really appreciate your time for posting this up :)

Javascript keydown function is only being called once

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).

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/

Categories

Resources