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.
Related
I am very new to JavaScript and HTML and CSS. I have read through my code multiple times and I can't seem to figure out what makes it not work. It is not returning any errors, but it's not working as expected. I'm trying to get a square on the screen to move on the press of WASD. I got the square to appear but nothing happens when WASD is pressed. I feel like the solution must be simple but I can't figure it out.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body onkeypress="move(event)">
<style>
#block {
width: 50px;
height: 50px;
background-color: #555;
margin-top: 0px;
margin-left: 0px;
}
</style>
<div id="block"class="block"></div>
<script>
var blockX = 0;
var blockY = 0;
var keyPressed = 0;
function move(event) {
keyPressed = event.keyCode;
if (keyPressed === 87 || 83) {
moveY();
}
else if (keyPressed === 65 || 68) {
moveX();
}
}
function moveX() {
if (keyPressed === 65) {
blockX -= 3;
document.getElementById("block").style.marginLeft = blockX + "px"
}
else if (keyPressed === 68) {
blockX += 3
document.getElementById("block").style.marginLeft = blockX + "px"
}
}
function moveY() {
if (keyPressed === 87) {
blockY += 3;
document.getElementById("block").style.marginTop = blockY + "px"
}
else if (keyPressed === 83) {
blockY -= 3;
document.getElementById("block").style.marginTop = blockY + "px"
}
}
</script>
</body>
</html>
You need to compare the keyPressed variable like this
(keyPressed === 87 || keyPressed === 83)
Also, you can listen for a keydown event using the following function:
document.addEventListener("keydown", function(event) {
move(event)
});
var blockX = 0;
var blockY = 0;
var keyPressed = 0;
function move(event) {
keyPressed = event.keyCode;
if (keyPressed === 87 || keyPressed === 83) {
moveY();
} else if (keyPressed === 65 || keyPressed === 68) {
moveX();
}
}
function moveX() {
if (keyPressed === 65) {
blockX -= 3;
document.getElementById("block").style.marginLeft = blockX + "px"
} else if (keyPressed === 68) {
blockX += 3
document.getElementById("block").style.marginLeft = blockX + "px"
}
}
function moveY() {
if (keyPressed === 87) {
blockY += 3;
document.getElementById("block").style.marginTop = blockY + "px"
} else if (keyPressed === 83) {
blockY -= 3;
document.getElementById("block").style.marginTop = blockY + "px"
}
}
#block {
width: 50px;
height: 50px;
background-color: #555;
margin-top: 0px;
margin-left: 0px;
}
<div id="block" class="block"></div>
I have disabled scrolling by pressing spacebar using code
in-line(434)
And I use code in-line(427-432) to play/pause video by pressing spacebar anywhere in body.
// So how to enable white-spaces in textarea?
And how to disable playing/pausing video by pressing spacebar in textarea? //
I have tried code in-line(433) to enable white-spaces in textarea but it doesn't work.
https://imgur.com/a/morZomC
427-432:
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function() {
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2); } });
$("body").on("keydown", function(e) { if (e.keyCode == 32) {
if (document.querySelector("video").playing) {
$("video")[0].pause(); } else {
$("video")[0].play(); } } });
433:
$("#comment").on("keydown", function(e) { if (e.keyCode == 32) { return true; } });
434:
$(document).keydown(function(e) { if (e.which == 32) { return false; } });
In your document listener, only return false if the target of the event is not a textarea:
$(document).keydown(function(e) {
if (e.which == 32 && e.target.tagName !== 'TEXTAREA') {
return false;
}
});
body {
height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
Or, to additionally permit spaces in inputs:
$(document).keydown(function(e) {
if (e.which == 32 && !['TEXTAREA', 'INPUT'].includes(e.target.tagName)) {
return false;
}
});
body {
height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
<input>
I have a set of buttons and you can navigate them using the left and right arrow keys, but im trying to implement up and down key presses aswell but adding .prev(-3) doesnt seems to work, so I was just wondering if its possible to do that?
I have setup a test of what im doing here
$(document).keydown(
function(e)
{
if (e.keyCode == 39) {
$("button:focus").next().focus();
}
if (e.keyCode == 37) {
$("button:focus").prev().focus();
}
if (e.keyCode == 40) {
$("button:focus").next(+3).focus();
}
if (e.keyCode == 38) {
$("button:focus").prev(-3).focus();
}
}
);
Working fiddle.
I would use nextAll and prevAll in combination with eq:
$("button:focus")
.nextAll() // get all following siblings
.eq(2); // get third from the set (zero based)
$("button:focus")
.prevAll() // get all previous siblings
.eq(2); // get third from the set (zero based)
Prev(number) is not supported by jquery but you can call it multiple times, see below code
$(document).keydown(
function(e)
{
if (e.keyCode == 39) {
$("button:focus").next().focus();
}
if (e.keyCode == 37) {
$("button:focus").prev().focus();
}
if (e.keyCode == 40) {
$("button:focus").next().next().next().focus();
}
if (e.keyCode == 38) {
$("button:focus").prev().prev().prev().focus();
}
}
);
working Code
i used to do like this but i changed to this Fiddle
I prefer to use tabindex
i count my buttons, input, select
i add to them tabindex by each
last i focus it by its index
let el=$('button');
for(var i = 1; i<=el.length; i++){
el.eq(i-1).attr('tabindex',i);
}
$('button').unbind().on('keydown', function(event) {
let currentTabIndex = $(this).attr('tabindex');
let el = $('button');
switch (event.which) {
case 38:
currentTabIndex = parseInt(currentTabIndex) - 1;
if (currentTabIndex == 0) {
$("[tabindex=" + el.length + "]").focus()
} else {
$("[tabindex=" + currentTabIndex + "]").focus()
}
break;
case 13:
case 40:
currentTabIndex = parseInt(currentTabIndex) + 1;
if (currentTabIndex == el.length+1) {
$("[tabindex=" + 1 + "]").focus()
} else {
$("[tabindex=" + currentTabIndex + "]").focus()
}
break;
}
});
button:focus{
border:1px solid red;
background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
all you need is select your buttons good on selecter
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>
Thanks in advance for your attention,
I'm using the W3 PHP AJAX Live Search Example and it's already integrated on this site. It's just about perfect. I wish to use arrows on keyboard, up (or left) and down (or right), to focus results inside of <div id="livesearch">. Than, on focus press Enter ⏎ key to load.
In HTML head :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
#livesearch {
min-height: 155px;
}
#livesearch a:hover {
text-decoration: none;
background-color: rgba(0,0,0,0.05);
}
#livesearch a {
text-transform: capitalize;
font-size: inherit;
padding: 5px 13px;
display: block;
}
#livesearch .selected {
text-decoration: none;
background-color: rgba(0,0,0,0.05);
}
</style>
</head>
HTML Form :
<body>
<form method="post" id="myfrm">
<input type="text" name="search" class="form-control search" placeholder="Just start typing..." autofocus="">
</form>
<div id="livesearch"><div>
</body>
AJAX function :
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
Jquery :
<script>
$(document).ready(function ($) {
$('.search').keyup(function (e) {
var key = e.keyCode;
if (key == 40 || key == 38 || key == 13) {
return false;
}
var str = $('.search').val();
showResult(str);
});
$('#myfrm').on("keydown", ".search", function (e) {
var $listItems = $('#livesearch a');
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
if (key != 40 && key != 38 && key != 13)
return;
//$listItems.removeClass('selected');
if (key == 40) // Down key
{
$listItems.removeClass('selected');
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
} else {
$current = $selected.next();
}
console.log("Current : "+$current);
}
else if (key == 38) // Up key
{
$listItems.removeClass('selected');
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
} else {
$current = $selected.prev();
}
}
else if (key == 13) // Enter key
{
$current = $listItems.filter('.selected');
$current.trigger('click');
return false;
}
$current.addClass('selected');
});
});
</script>
Retrieve data in input search box from livesearch data :
<script>
$(document).ready(function ($) {
$("body").on("click", "#livesearch a", function(e){
e.preventDefault();
var data = $(this).text();
$(".search").val(data);
$('#livesearch').html('');
});
});
</script>
If you want used instead of ajax showResult(str) using ajax+jquery for data retrieve livesearch.php so, you can used bellow code :
<script>
$(document).ready(function ($) {
$('.search').keyup(function (e) {
var key = e.keyCode;
if (key == 40 || key == 38 || key == 13) {
return false;
}
var str = $('.search').val();
$.ajax({
context: this,
url: 'livesearch.php',
type: 'get',
dataType: 'html',
data: {
q: str,
},
beforeSend: function () {
console.log("Loadding...");
}
}).done(function (response) {
$("#livesearch").html(response);
});
});
});
</script>
document.getElementById("yourtextfield").addEventListener("keyup",function(event){
var livesearchelem = document.getElementById("livesearch");
var childrens = livesearchelem.getElementsByTagName("a"); //Get only hyperlinks
var key = event.keyCode;
var selected = this.selectedResultNumber;
if (key == 38){ //Arrow up
if (childrens.length === 0){ return; }
if (!selected){ //If 'selectedResultNumber' is undefined
childrens[childrens.length - 1].style.backgroundColor = 'blue';
childrens[childrens.length - 1].style.color = 'white';
//Store the selected number into this element
this.selectedResultNumber = childrens.length - 1;
}
else if (selected > 1){
//Restore the previous selected element's style
childrens[selected - 1].style.backgroundColor = 'white';
childrens[selected - 1].style.color = 'black';
//Set the new selected element's style
childrens[selected - 2].style.backgroundColor = 'blue';
childrens[selected - 2].style.color = 'white';
//Decrease the selected number by 1
this.selectedResultNumber--;
}
}
else if (key == 40){ //Arrow down
if (childrens.length === 0){ return; }
if (!selected){ //If 'selectedResultNumber' is undefined
childrens[0].style.backgroundColor = 'blue';
childrens[0].style.color = 'white';
//Store the selected number into this element
this.selectedResultNumber = 1;
}
else if (selected < childrens.length){
//Restore the previous selected element's style
childrens[selected - 1].style.backgroundColor = 'white';
childrens[selected - 1].style.color = 'black';
//Set the new selected element's style
childrens[selected].style.backgroundColor = 'blue';
childrens[selected].style.color = 'white';
//Increase the selected number by 1
this.selectedResultNumber++;
}
}
else if (key == 13){ //Enter key
if (childrens.length === 0){ return; }
//Trigger click event on the selected element
childrens[selected - 1].click();
}
else{ //Searching in progress
delete this.selectedResultNumber;
//Your search function goes here
}
});