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.
Related
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();
}
}
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...");
}
This question already has an answer here:
override existing onkeydown function
(1 answer)
Closed 7 years ago.
I am trying to make a chrome extension that modifies the text in an active text area of a Facebook chat window. But I want the change to take place only when the user presses the enter key so that the text doesn't change while it is still in the textarea. I want it to happen using javascript and make it feel like it's happening in the background although I want it to get triggered on the keydown event of the enter key.
Now the relevant JavaScript for the chat window's textarea in Facebook is:
<textarea class="blah"
onkeydown="window.Bootloader && Bootloader.loadComponents(["control-textarea"],
function() { TextAreaControl.getInstance(this) }.bind(this)); ">
</textarea>
And in my extension's JavaScript file. I bind the keydown event using something like this:
//elem is bound to the focussed textarea object
elem.onkeydown = function(evt) {
if(evt.keyCode == 13){
//Some javascript code I want to execute here...
}
};
I think as soon as the user presses the enter key, the textarea is cleared and some sort of a post request is made. So I lose the scope of the text I wanted to modify using JavaScript. I checked that the enter key binding is working for my extension by pressing shift + enter, and it modified the text without a problem. So my script is working fine.
However I want my script to be executed before the textarea is cleared and the post request is made. I just don't want the user to see the text getting modified.
Can I add/modify the keybinding of the textarea used by Facebook as shown above in my script for the google chrome extension? Any help is deeply appreciated.
There are a million duplicates of this question on here, but here goes again anyway:
You can use target.addEventListener(type, listener[, useCapture]); In your case, it would be
document.addEventListner(keypress, function(event) { //You can use keydown too
if (event.which === 13) { // Value for Enter key if keydown or keyup used, use event.keyCode
//some code that you want to add
}
}
If you are using jQuery, you can use
$(document).keypress(function(event){
if (event.which === 13) {
// Your code here
}
});
P.S. - In case of adding crossbrowser support, you should use something like this:-
if (target.addEventListener) {
target.addEventListener('keypress',myFunction,false);
}
else if(target.attachEvent) {
target.attachEvent('onkeypress', myFunction, false);
} else {
target.onkeypress = myFunction;
}
// Here myFunction is the callback where you would check for the character code and your custom code
I have currently an eventlistener listening for when a user enters an email address in a textbox on an html website. It then displays an alert when it detects an email address is being entered. Currently I have set it up whereby it detects the event blur then checks whether it meets the regex then an alert will display. This creates many alerts and is not very accurate as the alert
I need the eventlistener to listen for when the tab key specifically is pressed. I know I need to use KeyCodes but have not used them before. This eventlistener is currently working dynamically as it is a Firefox AddOn that scans a webpage so the eventlistener is not specifically attached to a specific input box.
Code:
vrs_getWin.document.getElementsByTagName("body")[0].innerHTML = bodyContents;
var inputFields = vrs_getWin.document.getElementsByTagName("input");
for(inputC=0; inputC < inputFields.length; inputC++) {
var elementT = inputFields[inputC].getAttribute("id");
inputFields[inputC].addEventListener("blur", function(){
var emailPattern = /(\w[-._\w]*\w#\w[-._\w]*\w\.\w{2,3})/g;
var resultEmail = emailPattern.test(vrs_getWin.document.getElementById(elementT).value);
if(result) {
prompts.alert(null, "Test", vrs_getWin.document.getElementById(elementT).value);
}
}, false);
}
Any help with this will be much appreciated.
I think from a UX stand point, I would not recommend using a javascript alert to notify the user of a problem, especially if you want the notification to happen when they have completed a single form input. The blur event would be my recommendation, and use some other visual cue to notify the user.
But, if you want to go with the tab key, the event your looking for is 'keydown', or 'keyup'. To use it you listen for the keydown event then check if the event.keyCode == '9'. (tab key)
document.addEventListener('keydown', function(e){
if( e.keyCode == '9' ){
alert('You pressed the tab key.');
}
}, false);
To get the keycodes of keys I like to pop open a console and type in:
document.addEventListener('keydown', function(e){
console.log( e.keyCode );
}, false);
Then when you press a key, it will output the keycode for that key.
I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}