js - trigger generic function on space bar press anywhere on document - javascript

I have a colour guessing game with six different colour squares and an rgb code at the top of the page. The game works and the game resets via function - resetUI() - when a reset button on the page is clicked.
However, I want to trigger the resetUI function whenever the space bar is pressed. I have the following code, it doesn't throw any errors but it also doesn't work:
var body = document.querySelector("body");
body.addEventListener("keydown",function(){
if(this.key === " "){
resetUI();
}
});
I am fairly certain my use of "this" is wrong but I can't think of an alternative.
I have searched MDN and stackOverflow but I haven't seen a solution to this problem. Thanks.

key belongs to the event (which is passed into the event handler), not the body (which is what this refers to).
The next problem you will have is when you add an input or textarea to the page and anytime the user put a space into the input it will run your function.. You can check against the target to make sure the input isn't receiving the keystroke before you fire your function..
var body = document.querySelector("body");
body.addEventListener("keydown",function(e){
var isInput = ~["TEXTAREA", "INPUT"].indexOf(e.target.tagName);
if(e.key === " " && !isInput){
// resetUI();
console.log("u clicked spacebar, and it wasn't in an input");
}
});
<input />

You have lot of unnecessary code. And you should receive the event object from callback function to check against which key got pressed.
To check spacebar you shouldn't check against " " instead you have to check the keyCode of event.
document.body.onkeydown = function(e){
if(e.keyCode == 32){
console.log("space bar pressed");
resetUI();
}
}

Related

JavaScript Alert not disappearing when ok is clicked

I have created a JQuery dynamic table here and I'm trying to implement input checking to make sure only the numbers are saved. The cell is updated either by clicking outside of it or by pressing the enter button and what I am trying to achieve is having an alert whenever an invalid input is entered.
The 'focusout' function alert is is working perfectly. The 'keypress' function alert on the other hand is behaving strangely, the alert message is popping out as normal however it doesn't go away no matter how many times I click ok.
According to console.log() the alert is triggering the 'focusout' function somehow. But even if that was the case, I don't understand how that is causing the error since the 'focusout' function works fine. I've tried to use $(this).focus() after the alert but this didn't work. Any Idea what I may be missing?
Thanks in advance
$(document).on('keypress', '.row_data', function (event) {
if (event.which === 13) {
event.preventDefault()
if (isNaN($(this).html())) {
alert("Enter valid number")
} else {
var elem = $(this)
saveValue(elem)
}
}
});
/* Saves the edited cell data when user clicks outside the cell */
$(document).on('focusout', '.row_data', function (event) {
event.preventDefault();
if (isNaN($(this).html())) {
alert("Enter valid number")
} else {
var elem = $(this)
saveValue(elem)
}
});
EDIT
So here is my HMTL for context. I am using Handlebars to create a table but basically all my cells are like this..
<span class="row_data" edit_type="click" col_name="col_1">{{col_1}}</span>
</td>
<td>£
<span class="row_data" edit_type="click" col_name="col_2">{{col_2}}</span>
</td>
<td>£
<span class="row_data" edit_type="click" col_name="col_3">{{col_3}}</span>
</td>
and I'm using JQuery to make the cells editable like this...
/* Makes each cell on the table editable */
$(document).on('click', '.row_data', function (event) {
event.preventDefault();
if ($(this).attr('edit_type') === 'button') {
return false;
}
$(this).closest('span').attr('contenteditable', 'true');
$(this).css("background-color", "beige").css('padding', '5px');
$(this).focus();
})
I've made some changes below to your code and have commented on it fully. It's best to not repeat code whenever possible, and just maintain a single function and trigger that using various methods rather than having to ensure two different functions are maintained separately.
You are currently triggering your alert multiple times, we can rationalize the code a bit to avoid the two different functions triggering the warning.
I think you can simplify things by using:
$(":focus").blur();
This removes the focus from whichever element is in focus.
I've assumed your .row_data is an input, so have also used .val() rather than .html(), you might need to change this back depending on your use case.
Let me know if you were hoping for something else.
// I would recommend using keyup rather than keypress
$(document).on('keyup', '.row_data', function(event) {
// Check if it is a return
if (event.which === 13) {
// Remove focus
// This will triger the function below, it'll be easier to manage a single function
$(':focus').blur();
// Prevent default
event.preventDefault()
}
});
/* Saves the edited cell data when user clicks outside the cell */
$(document).on('focusout', '.row_data', function(event) {
// Prevent default
event.preventDefault();
// Check if NaN
// Used .val() - not sure if you need to use .html in your use case
if (isNaN($(this).val())) {
// Notify user
alert("Enter valid number")
} else {
// Pass element to save
saveValue($(this))
}
});
// Test saving function
function saveValue(elem) {
// Send to console to prove it works
console.log("Saving " + elem.val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="row_data">
Hi having your HTML here will help suggest a better soultion, but the simple guess is that you are creating a loop, with your events.
You said the keypress event is the problem, just for testing purposes have you tried changing keypress to keydown/keyUp.
Also i sugges changing the alert to console.log, for easier debuging.

Javascript Alert cannot be entered

is there any way to block Enter Keyboard when an alert box is show up? So user need to press Esc or Click the Ok button to remove the alert.
<script>
alert('Hello');
</script>
As stated by the comments before me, the standard javascript alert:
alert("hello world!");
Is a feature that is handled, styled, and executed by the browser outside the scope of javascript control.
With that said you can do this fairly easily by making a custom popup box.
I'm not going to go over the styling very much, but below is some code you could build on for a styled box:
<div id="alertBox" style="position:absolute;height:100%;width:100%;z-index:9999;background:white">
<div id="alertText" style="position:relative;text-align:center;top:45%">
You must press "esc" to escape!
</div>
</div>
The javascript however I will explain in more detail. This is the code:
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
document.onkeypress = function(e){
var key = code(e);
if(key == 27){
//run some code, they pressed the esc key
document.getElementById('alertBox').style.display = "none";
}
};
The first 4 lines of code store what key was pressed into a variable called "e".
The document.onkeypress function starts listening for when a key is pressed. The "e" variable is passed into the function and then saved into a variable named "key" for clarity.
The "key" variable is then tested against the "esc" keys number on the keyboard which is 27. If the "key" equals 27 than we run some code, if it does not we ignore the keypress.
The code we run here removes the alert box we made.
I hope that helps!
P.s. This answer does not use jQuery, but jQuery would make it less code if you already have it in your project.

How to detect ENTER keypress/ or the "GO" button in the Address Bar?

I want to detect the ENTER keypress of the Address Bar and also, the "Go(to the specified URL)" button using Javascript.
As per my previous efforts using "keycode==13" did not work as required.
say, in the following code:
window.onkeypress = testKeyEvent;
function testKeyEvent(e) {
if (e.keyCode == 13) //We are using Enter key press event for test purpose.
{
alert('Enter key pressed');
}
else //If any other button pressed.
{
alert('Not Enter key pressed');
}
} </script>
I want first the Alert box to be displayed,after I have typed any URL(valid or not) in the address box and Pressed ENTER/ Clicked GO button and then go to specified URL.
Is it Possible? I know I am missing out on a lot of things, Please mention about them.
If I am interpreting your question correctly, I don't think you can do this, because the context in which the JavaScript runs stops at the Document (meaning, JavaScript doesn't even quite know that the browser itself exists).
You can't detect the keystroke because it's outside your window, but you can detect navigation away from your page like
window.onbeforeunload = function () {
alert("Leaving page...");
}

How to activate function after the keypress?

Im building a autocomplete tool for my website. I want it to search for partial matches (it works only when "*" is the last character)
So I have this code:
<script type="text/javascript">
$('.search-form').click(function () {
var self = this;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var searchfield = $('.input-block-level');
searchfield.val(searchfield.val() + "*");
self.submit();
});
</script>
What it does is it gives me "*" immediately after clicking in search field and submits.
I need the function that puts the asterisks as the last symbol immediately after clicking (so when person starts typing the "*" is the last character) and waits for person to click submit (or not).
Any ideas anyone?
Please help
I'm assuming the .search-form that is being clicked on is the entire form? So when you click within the search box to type, the entire callback function for your click object is being run, which includes the self.submit().
I think you need to separate the two functionalities into their own event handlers. The searchfield.val(searchfield.val() + "*"); should be run when someone clicks into the $('.input-block-level');, and the submit function should be attached to the submit button itself.
What you are looking for, if I understood correctly, is an additional event listener for the keypress or keyup event. But you have to replace the asteriks every time the event fires. Try this:
$('.input-block-level').keypress(function(e) {
e.preventDefault();
e.stopPropagation();
if(/[a-z]/ig.test(e.key)) {
$(this).val($(this).val().replace(/\*$/g,'') + e.key + '*');
}
});

How to stop my code putting tabs into my text boxes

I have this piece of jQuery to detect when the cursor is inside the text box. The idea is to highlight the table row that the text box appears is.
$(".text").on("focus", function() { //do something });
The problem is that this code seems to be registering the tab key inside the text box. The cursor will still move to the next text box when I hit the tab key. However it always insert a tab space into the box as well!!
This is most unexpected and I must admit i'm a little confused by it...
Any help on this matter would be brilliant, thank you.
It seems that the alert() you are sending in the focus event is interrupting things in a strange way. You can fix this by setting a brief timeout before sending the alert; that ensures that the alert is sent AFTER the text box receives focus and the tab input has been handled.
setTimeout(function() { alert("box selected"); }, 1);
http://jsfiddle.net/5cjbcy9o/2/
Give every row a tabindex like this
var i=2;
$('tr').each($(this).attr('tabindex',i++))
A previous answer has addressed listening to the tab key, by checking the keyCode to see if it matches 9. However, the width of a tab character differs (also reliant on personal preferences), although it is either two or four spaces commonly. Therefore, you can append that white space to the value of the input text when the tab keydown event is detected.
In the following code I have opted to use four white spaces:
$(function () {
$(".text").on("focus", function () {
console.log("box selected");
}).on("keydown", function(e) {
if ((e.keyCode || e.which) == 9) {
e.preventDefault();
$(this).val($(this).val() + " ");
}
});
});
See proof-of-concept fiddle here: http://jsfiddle.net/teddyrised/5cjbcy9o/1/

Categories

Resources