For some reason this script isn't working in Firefox:
document.onkeydown=function keypress(e) {
if (e.keyCode == 27) {
window.location = "/edit"
};
};
It works fine in Chrome, but for some reason it's not working in Firefox.
Basically, what it does is load the /edit page when you press the escape key.
use:
document.onkeydown=function keypress(e) {
e=(e||window.event);
if (e.keyCode == 27) {
try{e.preventDefault();}//Non-IE
catch(x){e.returnValue=false;}//IE
window.location = "/edit";
};
}
The default-action for ESC is to stop loading the page,
so you must prevent from this behaviour, otherwise you cannot change the location.
Fiddle: http://jsfiddle.net/doktormolle/CsqgE/ (Click into the result-frame first before using ESC)
But however, you really should use another key.
A user expects that the loading of the current page stops if he uses ESC , nothing else.
The event handler is working for me: http://jsfiddle.net/Tm2PZ/
I suspect the lcoation you're setting is not valid.
Try setting window.location.href instead.
if you don't use 'Escape keyup or Escape keydown' for other things in your code, you can use 'keyup' to replace keypress**
document.body.addEventListener( 'keyup', function (e) {
e=(e||window.event);
if (e.key == "Escape") {
console.log('escape is pressed');
}
},false );
e.keyCode is depreciate, use e.key, add "console.log(e.key)" in your listener if you want to get key name
it is better, because it adapts to the keyboard which does not have the same composition and e.keyCode does not adapt
Related
I am doing this open source chrome extension and I would like to add a shortcut so that when the extension is open and I press Alt+C, then the content of a div is copied to my clipboard.
I am able to add shortcuts with a simple addEventListener:
var inputText = document.getElementById('textareaSource');
inputText.addEventListener('keypress', function (e) {
if (e.keyCode == 99) {
// alert("You pressed C!");
}
});
But apparently this way of adding shortcut doesn't allow shortcuts containing Alt. I tried this but I didn't get any alert:
if (e.altKey || e.ctrlKey || e.shiftKey)
alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
I am also able to add shortcuts via manifest/background.js (following this and this). This time, the Alt+C works but it can be triggered everywhere on Chrome and not only when my extension is opened.
Is there a way to get a middle ground: adding a shortcut containing Alt that is only triggered when my extension is opened?
The keypress event won't fire when a modifier key has been pressed, additionally, now it is deprecated.
As it say on the MDN, you should consider using keydown event instead, which supports the way you've tried.
event.keyCode is also deprecated, and event.key should be used instead.
So this code should work:
var inputText = document.getElementById('textareaSource');
inputText.addEventListener('keydown', function (e) {
if (e.key == "c" && e.altKey) {
// alert("You pressed Alt + C!");
}
});
I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?
I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode
This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.
The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo
This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo
I would like to call a function when the tab key is pressed within any field with the name="notes".
I tried the following but this doesn't fire (using IE 9). What do I have to change here to make this work at least in IE 8 and IE 9 ?
$('input[name=notes]').keypress(function(e) {
var code = e.keyCode || e.which;
if (code === 9) {
e.preventDefault();
myFunction();
}
});
The problem I think is in the type of event you're trying to listen to.
The keypress event is triggered when a char gets written into an input text, while tab key doesn't insert any character. It just blurs the input. Read more here.
You might be looking for the keydown event instead.
Have a look at this fiddle. Would it help to get you started?
JS
$('input[name=notes]').keydown(function(e) {
var code = e.keyCode || e.which;
if (code === 9) {
e.preventDefault();
myFunction();
alert('it works!');
}
});
I'm using onbeforeunload event to perform operations during the closing page.
I do not want the event to happen in the case of Refresh / F5.
Is there a way or other event to do this?
Unfortunately onbeforeunload event listens the page state in the browser. Going to another page as well as refreshing will change the page state, meaning onbeforeunload will be triggered anyway.
So I think it is not possible to catch only refresh.
But, if you'll listen and prevent Keypress via JavaScript, then it can be achieved.
Refresh can be done via F5 and CtrlR keys, so your goal will be to prevent these actions.
using jQuery .keydown() you can detect these keycodes:
For CtrlR
$(document).keydown(function (e) {
if (e.keyCode == 65 && e.ctrlKey) {
e.preventDefault();
}
});
For F5
$(document).keydown(function (e) {
if (e.which || e.keyCode) == 116) {
e.preventDefault();
}
});
I would use the keydown listener to check for F5 and set a flag var.
http://api.jquery.com/keydown/
Detecting refresh with browser button is not that easy/possible.
I wanted to add a message alert onbeforeunload, so my solution was this one:
$(document).ready(function(){
window.onbeforeunload = PopIt;
$("a").click(function(){ window.onbeforeunload = UnPopIt; });
$(document).keydown(function(e){
if ((e.keyCode == 82 && e.ctrlKey) || (e.keyCode == 116)) {
window.onbeforeunload = UnPopIt;
}
});
});
function PopIt() { return "My message before leaving"; }
function UnPopIt() { /* nothing to return */ }
Third line ($("a").click...) is to avoid showing the alert when navigating between sections of the web.
I have the code blow for tabbing through 2 fields and it has no effect in IE and Chrome, it seems it runs nothing (for example I get nothing when I put alert) and in Firefox it runs with some bug (it jumps twice there) where do you think the problem is, I'm developing in by ASP.Net and jQuery version 1.3.2
$(document).ready(function () {
$("#TextBox1").keypress(function (e) {
var kCode = e.keyCode || e.charCode;
if (kCode == 9) {
$("#TextBox2").focus();
}
});
});
I think the main problem is that you're using the keypress event, which should only be fired when a character is added to the input, not when any key (like TAB) is pressed.
To handle other key presses you will need to use keydown. However, testing that in your fiddle seems to still not work. To make it work (in Chrome at least), I had to prevent the default action:
$(document).ready(function () {
$("#TextBox1").keydown(function (e) {
e.preventDefault();
var kCode = e.keyCode || e.charCode;
console.log(kCode);
if (kCode == 9) {
$("#TextBox2").focus();
}
});
});
Here's an update fiddle. However, if I've understood your question correctly, all you're trying to do is change the focused element when the tab key is pressed... if that's right, why not just use the tabindex attribute instead?
The keypress event does not fire for tab (keycode 9). You'll need to use keyup or keydown.
If this is ASP.NET, you need to reference the controls by the ClientID:
$(document).ready(function () {
$("#<%=TextBox1.ClientID%>").keypress(function (e) {
var kCode = e.keyCode || e.charCode;
if (kCode == 9) {
$("#<%=TextBox2.ClientID%>").focus();
}
});
});