if condition depending on css - javascript

I have a problem which has bothered me for a day now and I can't get it right. I have a couple of keydown functions, that changes the background image in certain states, if the class 'active' is not in use.
Like this:
if ($('li').hasClass('active')) {
letterIndex = letterIndex + 1;
$(this).html(letters[letterIndex]);
}
else {
$('.content').css("background-image", "url(img/screen-back.jpg)");
$('li').blur(); // remove focus
}
The thing I want is that when you press up, the background image is updated to a new image (this works) and then with the new background active, I want to be able to press enter to go to a url (this doesn't work).
Example:
case key.enter:
if (letterIndex == 0 && $(this).hasClass('active')) {
$(this).prev().remove();
}
else if ($('.content').css('background-image') === 'url(img/screen-default.jpg)') {
// go to url
}
else {
$(this).closest('li').toggleClass('active');
}
break;
If the default background image is active, the if condition works, but if I change it to another image, nothing happens. Unfortunately I'm unable to add all the images but I've created a fiddle for reference. I would be very thankful to any kind of help in the right direction!
Fiddle

Try:
var letters = [
'<','.',',',';',':',
'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z',
'1','2','3','4','5','6','7','8','9','0'
];
$('li:first').focus().addClass('active');
$('li').on('click', function(e){
$('li').removeClass('active');
$(this).addClass('active');
})
$('li').on('keydown', function(e) {
e.preventDefault();
var keyCode = e.which;
key = {up: 38, down: 40, right: 39, left: 37, enter: 13};
letterIndex = letters.indexOf($(this).text());
switch(e.which) {
case key.up:
if ($('li').hasClass('active')) {
letterIndex = letterIndex + 1;
$(this).html(letters[letterIndex]);
}else {
$('.content').css("background-image", "url(img/screen-back.jpg)");
$('li').blur(); // remove focus
}
break;
case key.down:
if ($('li').hasClass('active')) {
letterIndex = letterIndex - 1;
$(this).html(letters[letterIndex]);
}else {
$('.content').css("background-image", "url(img/screen-check.jpg)");
$('li').blur(); // remove focus
}
break;
case key.right:
// check if li is not active, then move right
if ($('li').hasClass('active')) {
$('li:focus').removeClass('active');
$('li:focus').closest('li').next().focus().addClass('active');
} else if ($('li:last-child').is(':focus')) {
$('.content').css("background-image", "url(img/screen-check.jpg)");
$('li').blur(); // remove focus
}
break;
case key.left:
// check if li is not active, then move left
if ($('li').hasClass('active')) {
$('li:focus').removeClass('active');
$('li:focus').closest('li').prev().focus().addClass('active');
}else {
$('.content').css('background-image', 'url(img/screen-back.jpg)');
$('li').blur(); // remove focus
}
break;
case key.enter:
// check if the first item in array is chosen and active and delete
if (letterIndex == 0 && $(this).hasClass('active')) {
$(this).prev().remove();
}else if ($('.content').css('background-image', 'url(img/screen-default.jpg)')) {
alert('yes');
}else {
$(this).closest('li').toggleClass('active');
}
break;
}
});
http://jsfiddle.net/a91p86wv/7/

Use focus event to check inside up and down key events.
if ($(this).is(':focus')) {
letterIndex = letterIndex + 1;
$(this).html(letters[letterIndex]);
}else {
$('.content').css("background-image", "url(img/screen-back.jpg)");
$('li').blur(); // remove focus
}
Is this what you wanted to do?
http://jsfiddle.net/a91p86wv/5/

Related

Selecting next list item with down arrow

Given a list of divs, I need to be able to use the up and down arrow keys to navigate between items in the list, apply an .ag-menu-option-active class to the currently selected item, and on Enter key, trigger a click on the currently selected list item.
I'm currently able to iterate over the list of items, but on down arrow, it only logs out the second item in the list. As stated above, the user should be able to move up and down the list and have the active class applied to the currently selected item. When the user hits the Enter key, the associated list item should be clicked.
let columnMenuItems = document.querySelectorAll('.ag-menu-option');
document.addEventListener('keydown', e => {
if (e.key === 'ArrowDown') {
for (let i = 0; i < columnMenuItems.length; i++) {
if (columnMenuItems[i].classList.contains('ag-menu-option-active') === true) {
console.log("MENU OPTION SELECTED: ", columnMenuItems[i + 1])
columnMenuItems[i].click();
break;
}
}
}
});
JSFiddle link: link
if(columnMenuItems[i+1] !== undefined){
//add class to next
columnMenuItems[i+1].className= "ag-menu-option ag-menu-option-active"
columnMenuItems[i].className= "ag-menu-option"
}
you can write some other logic to add and remove class but this should work for arrow down.
You were missing the +/- when you are calling .click() method;
Also to prevent the undefined error you should add columnMenuItems-1 in first for loop.
Code should look like this -
if (e.key === 'ArrowDown') {
for (let i = 0; i < columnMenuItems.length-1; i++) {
if (columnMenuItems[i].classList.contains('ag-menu-option-active') === true) {
console.log("MENU OPTION SELECTED: ", columnMenuItems[i + 1]);
columnMenuItems[i].classList.remove('ag-menu-option-active');
columnMenuItems[i + 1].click();
columnMenuItems[i+1].classList.add('ag-menu-option-active');
break;
}
}
}
if (e.key === 'ArrowUp') {
for (let i = columnMenuItems.length - 1; i > 0; i--) {
//console.log("MENU OPTIONS: ", columnMenuItems[i]);
if (columnMenuItems[i].classList.contains('ag-menu-option-active') === true) {
columnMenuItems[i].classList.remove('ag-menu-option-active');
//if (e.key === 'Enter') {
columnMenuItems[i - 1].click();
columnMenuItems[i-1].classList.add('ag-menu-option-active');
//}
break;
}
}
}
Test it here (jsfiddle)

how to scrolltop using arrow navigation inside keyup search function?

I have a page where i will have keyup autocomplete search functionality. using arrow navigation i need to scroll down till end. how to add scroll tp function in jquery
Please check with autocomplete
https://jsfiddle.net/os5ko0v8/2/
$(document).ready(function(){
var people = ['Peter Bishop', 'Nicholas Brody', 'Gregory House', 'Hank Lawson', 'Tyrion Lannister', 'Nucky Thompson'];
var cache = {};
var drew = false;
$("#search").on("keyup", function(event){
var query = $("#search").val()
if($("#search").val().length > 2){
//Check if we've searched for this term before
if(query in cache){
results = cache[query];
}
else{
//Case insensitive search for our people array
var results = $.grep(people, function(item){
return item.search(RegExp(query, "i")) != -1;
});
//Add results to cache
cache[query] = results;
}
//First search
if(drew == false){
//Create list for results
$("#search").after('<ul id="res"></ul>');
//Prevent redrawing/binding of list
drew = true;
//Bind click event to list elements in results
$("#res").on("click", "li", function(){
$("#search").val($(this).text());
$("#res").empty();
});
}
//Clear old results
else{
$("#res").empty();
}
//Add results to the list
for(term in results){
$("#res").append("<li>" + results[term] + "</li>");
}
}
//Handle backspace/delete so results don't remain
else if(drew){
$("#res").empty();
}
});
});
You can capture the keycode on keyup
$(document).ready(function(){
var people = ['Peter Bishop', 'Nicholas Brody', 'Gregory House', 'Hank Lawson', 'Tyrion Lannister', 'Nucky Thompson'];
var cache = {};
var drew = false;
var currentSelection = 0;
var navigation = false
$("#search").on("keyup", function(event){
switch(event.keyCode) {
// User pressed "up" arrow
case 38:
navigation = true;
navigate('up');
break;
// User pressed "down" arrow
case 40:
navigation = true;
navigate('down');
break;
// User pressed "enter"
case 13:
navigation = true;
$("#search").val($("#res li.selected").text());
$("#res").empty();
break;
default:
navigation = false;
break;
}
if(navigation == false) {
var query = $("#search").val()
if($("#search").val().length > 0){
//Check if we've searched for this term before
if(query in cache){
results = cache[query];
}
else{
//Case insensitive search for our people array
var results = $.grep(people, function(item){
return item.search(RegExp(query, "i")) != -1;
});
//Add results to cache
cache[query] = results;
}
//First search
if(drew == false){
//Create list for results
$("#search").after('<ul id="res"></ul>');
//Prevent redrawing/binding of list
drew = true;
//Bind click event to list elements in results
$("#res").on("click", "li", function(){
$("#search").val($(this).text());
$("#res").empty();
});
}
//Clear old results
else{
$("#res").empty();
}
//Add results to the list
for(term in results){
$("#res").append("<li>" + results[term] + "</li>");
}
}
//Handle backspace/delete so results don't remain
else if(drew){
$("#res").empty();
}
}
});
});
function navigate(direction) {
if($("#res li.selected").size() == 0) {
currentSelection = -1;
}
if(direction == 'up' && currentSelection != -1) {
if(currentSelection != 0) {
currentSelection--;
}
} else if (direction == 'down') {
if(currentSelection != $("#res li").size() -1) {
currentSelection++;
}
}
setSelected(currentSelection);
}
function setSelected(menuitem) {
$("#res li").removeClass("selected");
$("#res li").eq(menuitem).addClass("selected");
}
#res {
margin: 0px;
padding-left: 0px;
width: 150px;
}
#res ul li {
list-style-type: none;
}
#res li:hover {
background: #110D3B;
color: #FFF;
cursor: pointer;
}
#res li.selected {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="output"><div>
<input id="search" type="text">

How to Javascript/html5 Input Keyboard in-order set (not in the same time)

I have create a simple game that need to press keyboard buttons exactly follow the step in order to move character. But I cannot figure out how to do it and all I found on the internet is about pressing multiple keyboard buttons in the same time. (set array and use &&)
Picture this: you have to press A then, B, C, and D to move character forward, or D,C,B,andA in-order to move back. All of these are not press at the same time, but follow the set.
So can someone tell me or give me some clue how to do that? Also, what about pressing button like double click mouse?- is it possible.
Thanks in advance.
Just something off the top of my head:
var aPressed = false;
var bPressed = false;
var cPressed = false;
var dPressed = false;
document.onkeydown = function (event) {
var key = event.keyCode;
switch (key) {
case 65:
aPressed = true;
break;
case 66:
if (aPressed) {
bPressed = true;
}
break;
case 67:
if (aPressed && bPressed) {
cPressed = true;
}
break;
case 68:
if (aPressed && bPressed && cPressed) {
dPressed = true;
}
break;
default: //Reset all buttons
aPressed = false;
bPressed = false;
cPressed = false;
dPressed = false;
break;
}
if (dPressed) {
//Move forward and reset pressed buttons
}
}
Hope this can help you a bit :)
EDIT:
as for the "double pressing" a button, you could combine it with something like this:
var presscount = 0;
var delay = 300;
document.onkeydown = function(){
presscount++;
if(presscount == 1)
{
setTimeout(function(){
if(presscount == 1)
{
//stuff to do on single press
}
else
{
//stuff to do on double press
}
}, delay);
}
}

detecting two keyboard buttons in javascript

im writing a simple canvas game and want to be able to move my character diagonally on the screen. how do I detect two keys pressed say up and right?
heres my code so far-
function keyHit(evt){
switch (evt.keyCode) {
case 38: /* Up arrow was pressed */
if (player2y >= 1){
player2y -= 4;
} else {player2y = 0;}
break;
case 40: /* Down arrow was pressed */
if (player2y <= 364){
player2y += 4;
} else { player2y = 365;}
break;
case 37: /* Left arrow was pressed */
if (player2x >= 1){
player2x -= 4;
} else {player2x = 0;}
break;
case 39: /* Right arrow was pressed */
if (player2x <= 665){
player2x += 4;
} else {player2x = 666;}
break;
}
}
Trap "keydown" and "keyup" events and maintain the list of keys that are currently pressed. Example:
pressed = {}
window.onkeydown = function(e) {
pressed[e.keyCode] = 1
handler(Object.keys(pressed).sort())
}
window.onkeyup = function(e) {
delete pressed[e.keyCode];
handler(Object.keys(pressed).sort())
}
function handler(pressed) {
document.getElementById("log").value = pressed
if(pressed == "38,39")
alert("Up+Right pressed!")
}
<textarea id="log"></textarea><br>click here first, then press some keys

Jump to a spefific div if key pressed on keyboard

I have a .aspx Page.
What iam trying to do is, that if i press "T" on the Keyboard, the side should jump to a specific div. Is there a way resolve that?
I tried with javascript:
document.body.onkeypressed
But always getting Errors. Can some help? Thanks
SOLUTION:
function shortcut(event) {
if (event.keyCode) {
keycode = event.keyCode;
}
else {
keycode = event.which;
}
switch (String.fromCharCode(keycode)) {
case ("1"):
document.getElementById('TblVerfuegbareDienstleistungen').scrollIntoView();
break;
case ("2"):
document.getElementById('TblReservierungen').scrollIntoView();
break;
}
}
onload = function() {
document.body.onkeypress = function() {
shortcut(window.event);
}
}
Well, this example with jQuery.
$('body').on('keydown',function(e){
if(e.which==84){
$(window).scrollTop($('#divID').offset().top);
$("#divID").focus();
}
});
FIDDLE
Example with JavaScript
window.onkeypress = function() {
var x;
x=event.which;
keychar=String.fromCharCode(x);
if(keychar == "t" || keychar == "T") {
//window.location.hash ="#div4"; // first time work but then scroll to top and hit 'T' it is not work.
document.getElementById('div3').scrollIntoView();
}
}
FIDDLE
<javascript>
window.onkeypress = function() {
var x;
if(window.event) // for IE8
{
x=event.keyCode;
} else if(event.which)//IE9/Firefox/Chrome/Opera/Safari
{
x=event.which;
}
keychar=String.fromCharCode(x);
if(keychar == "t" || keychar == "T") {
alert("Key T was pressed down");
}
}
</javascript>

Categories

Resources