Keydown event does not fire a function - javascript

I've made a simple code which should change visibility of box while certain key is pressed,but something is wrong because whichever button will be pressed it always says it's wrong.
This should work only while "f" key is pressed,right now it doesn't work at all...
const brick = document.querySelector('.brick');
window.addEventListener('keydown',function(e)
{
e.preventDefault();
if(e.keycode == 70)
{
let x = event.keyCode;
console.log(x);
brick.style.visibility = "visible";
} else {
let x = e.keyCode;
console.log(x);
console.log("You've pressed wrong button")
brick.style.visibility ="hidden";
}
});
Code is Here
I know i can use jquery but i would like to do this in pure JS
Greets

Slight syntax error:
if(e.keycode == 70)
should be:
if(e.keyCode == 70)
Notice the capital C.

This may helpful . After run the code press key "F" in the keyboard to see the red div
const brick = document.querySelector('.brick');
window.addEventListener('keydown',function(e)
{
e.preventDefault();
let x = e.keyCode;
if(x == 70)
{
//console.log(x);
brick.style.visibility = "visible";
}
else
{
//console.log(x);
//console.log("You've pressed wrong button")
brick.style.visibility ="hidden";
}
});
.brick
{
width:100px;
height:100px;
visibility: hidden;
background-color: red;
display:block;
}
<div class="brick" >
</div>

Related

Using jQuery to changing background colour of a div

I'm trying to change the background colour of my div when the user presses either C, M or Y. I need to use the keypress method, but for some reason my code doesn't work.
$(document).ready(function() {
$(document).keypress(function(event) {
if (event === 99) {
$(".light").css('background-color', "#00ffff");
} else if (event === 121) {
$(".light").css('background-color', "#00ffff");
} else if (event === 109) {
$(".light").css('background-color', "#00ffff");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>
You need to use event.which to determine which key was pressed. Here's working code:
$(document).ready(function() {
$(document).keypress(function(event) {
if (event.which === 99) {
$(".light").css('background-color', "#00ffff");
} else if (event.which === 121) {
$(".light").css('background-color', "#00ffff");
} else if (event.which === 109) {
$(".light").css('background-color', "#00ffff");
}
});
});
div.light {
width: 50px;
height: 50px;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>
You need to use the which value from the keypress event. I would also suggest that you use a switch-statment.
$(document).ready(function() {
$(document).keypress(function(e) {
var color = null;
switch (e.which || e.keyCode || 0) { // Cover all cases
case 99: // Key - C
color = '#00FFFF'; break;
case 109: // Key - M
color = '#FF00FF'; break;
case 121: // Key - Y
color = '#FFFF00'; break;
default:
color = '#FFFFFF';
}
$('.light').css('background-color', color);
});
});
.light {
width: 95vw;
height: 95vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>
Thanks to smarx for the heads-up about jQuery and which.

Toggle up/down with up down keys in auto suggest

I am trying to make auto-suggest using ajax with php and mysql. Auto-suggest is working well but I am getting problem with toggling up down with up down keys. I am following this jsfiddle as example for completing my work. But can't get why Navigate function is been called twice. Because it alerts twice when I press down keys.
jquery
var Navigate = function(diff){
displayBoxIndex += diff;
var oBoxCollection = $("#searched a .searchFull");
if (displayBoxIndex >= oBoxCollection.length) {
displayBoxIndex = 0;
alert("A");
}
if (displayBoxIndex < 0) {
displayBoxIndex = oBoxCollection.length - 1;
alert("B");
}
var cssClass = "selected";
oBoxCollection.removeClass(cssClass).eq(displayBoxIndex).addClass(cssClass);
}
$(document).on('keypress keyup', "#search", function (e) {
if (e.keyCode == 13 || e.keyCode == 32) {
$('.display_box_hover').trigger('click');
return false;
}
if (e.keyCode == 40) {
//down arrow
Navigate(1);
}
if (e.keyCode == 38) {
//up arrow
Navigate(-1);
}
});
HTML
<div id="searched" style="display: block;">
<a href="http://localhost/c2c/init/product/78">
<div class="searchFull">
</a>
<a href="http://localhost/c2c/init/product/77">
<div class="searchFull">
</a>
<a href="http://localhost/c2c/init/product/76">
<div class="searchFull">
</a>
<a href="http://localhost/c2c/init/product/73">
<div class="searchFull">
</a>
Here is the solution for your issue:
You call two events like: keypress and keyup. So, it will call twice.
Just remove one like here i remove keypress and here it works well.
$(document).on('keyup', function (e) {
if (e.keyCode == 13 || e.keyCode == 32) {
$('.display_box_hover').trigger('click');
return false;
}
if (e.keyCode == 40) {
//down arrow
//alert("down");
Navigate(1);
}
if (e.keyCode == 38) {
//up arrow
Navigate(-1);
}
});
Check Fiddle here.
And as per comment Here selected class not removed checked in firebug. See below image.
Hope it helps.

JavaScript:"onkeydown"and "onkeypress"

I want to capture the event of onkeydown to move a box but when I press the key constantly,there existing a delay,that is,when I press a key constantly,the box will move after a while.Please help me eliminate the delay.
If I understand you correctly I believe the delay you are referring to might be the default functionality of your keyboard. For example if you open a text-editor and press and hold space you notice it will do:
(move over a little) (wait) (start moving)
Keyboard events also work in this way. If you defined moving of your box to something similar to this:
document.addEventListener("keydown", function(e) {
var key = e.which;
if( key == 37 ) X -= speed;
if( key == 38 ) Y -= speed;
if( key == 39 ) X += speed;
if( key == 40 ) Y += speed;
});
Here is an example of the code above
You will notice this "type-writer" like behavior. To fix this you can use Booleans to detect when a key is pressed (true), then to detect when the pressed key is let go (false). In your screen update function check these Booleans for movement.
var LEFT = false , RIGHT = false, UP = false, DOWN = false;
...
document.addEventListener("keydown", function(e) {
var key = e.which;
if( key == 37 ) LEFT = true;
if( key == 38 ) UP = true;
if( key == 39 ) RIGHT = true;
if( key == 40 ) DOWN = true;
});
document.addEventListener("keyup", function(e) {
var key = e.which;
if( key == 37 ) LEFT = false;
if( key == 38 ) UP = false;
if( key == 39 ) RIGHT = false;
if( key == 40 ) DOWN = false;
});
...
// In update function
if( LEFT ) X -= speed;
if( UP ) Y -= speed;
if( RIGHT ) X += speed;
if( DOWN ) Y += speed;
Here is an example
Notice in the second example the movement is much smoother.
<html>
<head>
<style>
.box {
width: 100px;
height: 100px;
background: #ccc;
position: absolute;
top: 0px;
left: 0px;
}
.clear {
clear: both;
}
p {
margin-top: 100px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="box"></div>
<div class="clear"></div>
<p> Press Space Bar</p>
<script type="text/javascript">
$(document).ready(function(){
console.log("ready");
});
$(document).on('keydown', function(event){
var code = event.keyCode;
if (code == 32) {
var div = $('.box');
var left = div.position().left;
var new_left = left + 1;
console.log(new_left);
div.css({
'left': new_left + "px"
});
}
});
</script>
</body>
</html>
a JSfiddle Link
maybe this could give you a little help.
and try also to console.log on your event

Click a specified event on the input in keyboard: up, down, left, right

I need an event that gives one click right, up, down or left. Below is the logic:
if (gesture.left) {
Click Event for left direction
} Else if (gesture.right) {
Click Event for right direction
}
I need to detect only one condition after the click button
Try this code:
$(function(){
$('html').keydown(function(e){
if(e.keyCode == 37) { // left
}
else if(e.keyCode == 39) { // right
}
else if(e.keyCode == 38) { // up
}
else if(e.keyCode == 40) { // down
}
});
});
arrow keys are only triggered by onkeydown, not onkeypress
keycodes are:
left = 37;
up = 38;
right = 39;
down = 40;
or you can look at this thread sample

Javascript Toggle on keydown

I'm pretty new when it comes to getting my head around JS functions. Everything I've used before, I've tended to use as-is, but I've been trying to combine and modify a function to get a Div to toggle (height & opacity) on a specific keypress. I have the first part (can get the div to show on a 'ctrl + o' combo), but can't combine it with an if statement to show or hide, based on current display status.
Current working 'show only' JS:
$(document).keydown(function (e) {
if (e.keyCode == 79 && e.ctrlKey) {
document.getElementById('thediv').style.height = 'auto';
document.getElementById('thediv').style.opacity = '1';
return false;
}
});
Not working 'toggle on/off' JS (I've tried changing this all over the place; this is more to give an idea of what I'm trying to achieve):
$(document).keydown(function (e) {
if (e.keyCode == 76 && e.ctrlKey) {
function toggler('thediv') {
var myDiv = document.getElementById('thediv').style.height;
if (myDiv == "auto") {
document.getElementById('thediv').style.height = "0px";
document.getElementById('thediv').style.opacity = "0";
} else {
document.getElementById('thediv').style.height = "auto";
document.getElementById('thediv').style.height = "1";
}
}
}
});
Any help would be really appreciated!
You want to show and hide an element, why set its height and visibility? Just show/hide it with toggle.
$(document).keydown(function (e) {
if (e.keyCode == 76 && e.ctrlKey) {
$("#thediv").toggle();
}
});
Looking at your code
$(document).keydown(function (e) {
if (e.keyCode == 76 && e.ctrlKey) {
//This funciton is never called, you define it, do not call it!
function toggler('thediv') { //<-- Error Here, you have a string as an argument?
var myDiv = document.getElementById('thediv').style.height;
if (myDiv == "auto") {
document.getElementById('thediv').style.height = "0px"; //<--Bad practice using document.getElementById('thediv') over and over. Store it into a variable and reference it.
document.getElementById('thediv').style.opacity = "0";
} else {
document.getElementById('thediv').style.height = "auto";
document.getElementById('thediv').style.height = "1";
}
}
}
});

Categories