I have a page where I have to close a dialog when Esc is pressed. I wrote the following simplified code example for this task:
<html>
<head>
<script language="JavaScript">
function keyUpExample() {
alert('on' + event.type + ' event fired by ' + '"' + event.srcElement.id + '" ' + ' ' + event.which)
}
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
Trying keyUp event: Press any key...
</body>
</html>
This works as expected under Chrome but is NOT working under IE 7. Is there any workaround on order to cope this problem?
Thanks in advance!
Key events don't have to be caught by the body, but document or window works across browsers. Also, keyCode returns the correct value for keyup or down events.
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<html>
<head>
<script>
function keyUpExample(e){
e=e || window.event;
var who= e.target || e.srcElement;
alert(e.type+' caught at '+who.nodeName+ ': key #'+e.keyCode)
}
window.onload=function(){
document.onkeyup= keyUpExample;
document.body.onkeyup= keyUpExample;
}
</script>
</head>
<body>
Trying keyUp event: Press any key...
</body>
</html>
Pass event as an argument to the callback, and check for window.event for IE.
<html>
<head>
<script>
function keyUpExample(e) {
e = e || window.event;
alert('on' + e.type + ' event fired by ' + '"' + e.srcElement.id + '" ' + ' ' + e.which)
}
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
Trying keyUp event: Press any key...
</body>
</html>
Demo
element.onkeyup reference
However
You're better off using a library which smooths out all the ugly cross-browser inconsistencies. Take your pick: jQuery, Prototype, YUI, Dojo, MooTools, RightJS...
Are you allowed to use jQuery? If so, then you can accomplish it with .keyup().
Using jQuery also means you can generally leave the cross-browser worries to somebody else.
try
function keyUpExample(e) {
var evt = e || event;
alert('on' + evt.type + ' event fired by ' + '"' + ((evt.srcElement)?evt.srcElement.id:evt.target.id) + '" ' + ' ' + ((evt.which)?evt.which:evt.keyCode))
}
It is actually very simple, a raw JavaScript solution could look kinda like this
function callback(event) {
if (event.keyCode == 27) {
alert('Here you go!');
}
}
if (document.addEventListener) {
document.addEventListener('keydown', callback, false);
} else {
document.attachEvent('onkeydown', callback);
}
Just attach it to the document no need for any onload trickery.
Also, as people suggested you, check RightJS, it's very lightweight and friendly, and you will be able to do things like those :)
http://rightjs.org/plugins/keys
Related
I am trying to catch the "ctrl + f" event in Javascript.
Even though, any letter on my keyboard fires an event,
"ctrl" does not.
Could you help me, please?
Below, is the code I execute:
if (event.ctrlKey && event.key === 'f') {
event.preventDefault();
document.querySelector("#search").focus();
}
Use the 'onkeydown' event to capture the ctrl event.
<html>
<head>
<title>ctrlKey example</title>
<script type="text/javascript">
function checkKeyPress(e){
if (event.ctrlKey ) {
event.preventDefault();
alert(
"CTRL key pressed: " + e.ctrlKey + "\n"
);
}
}
</script>
</head>
<body onkeydown="checkKeyPress(event);">
<p>Press CTRL</p>
</body>
</html>
Assume we have this code:
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var p = 0;
function reset()
{
// some efforts
}
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
if(key == 38 || key == 40)
{}
else if(e.altKey)
{
alert('altkey pressed');
}
else
{
// Another THING!
}
};
};
</script>
</head>
<body style="padding:30px; font-size:30px;font-family: Courier;">
<span onclick="reset();" accesskey="r"></span>
</body>
</html>
It works great in Firefox but not in IE an Chrome.
When I change alt into shift it works on all browsers. but as you may notice, I wanted to use this for Shortcut key and I think this is a problem of Alt key in Chrome and IE (because both use Alt for accesskey attribute but Firefox uses Alt+Shift as mentoned here).
So guys what you suggest me to do ?
You can not detect alt button on chrome because it enables the window menu, so your page lose focus and the event "keypress" is not called. The event "keydown" on the other hand is called so you can use it with no problem.
I have a div <div id="Country">India</div> . I want to execute some code (say JavaScript function) whenever the div value changes. How can I listen to changes on the div value? Do i need to use Jquery for this?
an easy jquery solution is to use a custom event and trigger it yourself when you change the DOM:
$("#country").html('Germany').trigger('CountryChanged');
$('#country').on('CountryChanged', function(event, data) {
//contentchanged
});
I have prepared a small demo for you. Its a little crude but I am sure You can improve it ;).
Happy Coding :)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#ChangeText").click(function(){
var value = $("#DivText").val();
$("#Country").text(value);
});
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
alert('Content added! Current content:' + '\n\n' + this.innerHTML);
} else {
alert('Content removed! Current content:' + '\n\n' + this.innerHTML);
}
});
});
</script>
</head>
<body >
<input type="text" id="DivText" />
<button id="ChangeText"> Change Div Text </button> <br /> <br />
<div id="Country">India</div>
</body>
</html>
You can listen to events triggered by the MutationObserver DOM API :
https://developer.mozilla.org/en/docs/Web/API/MutationObserver
Try this Demo, It's in Cracker0dks's link http://jsbin.com/ayiku and this is the code http://jsbin.com/ayiku/1/edit
Try this within script tag:
$(document).ready(function(){
var new_country1 = "";
var new_country2 = "";
var func_flag = 0;
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
new_country1 = this.innerHTML;
if(new_country1 != new_country2 && func_flag == 1) {
country_changed_function();
}
} else {
new_country2 = this.innerHTML;
}
func_flag = 1;
});
});
function country_changed_function(){
alert('country changed.');
}
Here "country_changed_function" is function trigger on country div innerHTML got changed.
I have a web application that I am testing with HP's UFT software. Within my application,
there is a text field with an onkeydown attribute. When a key is pressed within the text field, a function is called which triggers different actions depending on what key was pressed. I am interested in the enter key. When the enter key is pressed, rows are created within the form. How can I simulate the enter key being pressed within the field?
I have tried
field1.Set Chr(13)
field1.FireEvent "onkeydown"
but it doesn't trigger the event.
I am trying aviod using the SendKeys command.
If you use device replay mode (as described in this answer) and send a vbCRLF your application will be able to see the enter key.
Setting.WebPackage("ReplayType") = 2 ''# Changes to device mode
Browser("Enter").Page("Enter").WebEdit("WebEdit").Set "a" & vbCRLF
This works (on IE) for the following sample page:
<!DOCTYPE html>
<html>
<head>
<title>Enter</title>
<script>
function okd() {
if (event.keyCode == 13)
alert("Got enter");
}
</script>
</head>
<body>
<textarea onkeydown="okd()"></textarea>
</body>
These are the some methods i have tried for simulate keyboard events and worked for me..
Set oShell = CreateObject("WScript.Shell")
oShell.SendKeys "{TAB}" ' Click Tab Key
oShell.SendKeys "{ENTER}" ' Click Enter\Return
Also i have used
Type micAltDwn + "RETURN" + micAltUp ' Click Tab Key
Type micAltDwn + "TAB" + micAltUp ' Click Enter\Return
If u Want to enter characters
oShell.SendKeys "{h}" ' Click h Key
oShell.SendKeys "{i}" ' Click i Key
Type micAltDwn + "h" + micAltUp ' Click h Key
Type micAltDwn + "i" + micAltUp ' Click i Key
WORKING FIDDLE
$(document).keyup(function (e) {
$("#my_id").keyup(function (e) {
if (e.keyCode == 13) {
alert("Enter Simulated!!!")
//your function goes here!!!
}
});
});
UPDATE:2nd demo
In Gmail, for example, when one presses Ctrl + B, instead of it getting passed to the browser (which would normally bring up some sort of bookmark manager), it hijacks it for formatting purposes, i.e. turn on bold formatting for the message ur in the middle of comoposing. Same for Ctrl+i, Ctrl+u.
How is this done?
You would attach an onkeydown or onkeyup event handler to the global document object. For example, if I wanted to make the title bar change to "asdf" each time Ctrl-M was pressed, I would register the event handler through window.onload, like this:
window.onload = function()
{
document.onkeydown = function(event)
{
var keyCode;
if (window.event) // IE/Safari/Chrome/Firefox(?)
{
keyCode = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyCode = event.which;
}
var keyChar = String.fromCharCode(keyCode).toLowerCase();
if (keyChar == "m" && event.ctrlKey)
{
document.title = "asdf";
return false; // To prevent normal minimizing command
}
};
};
W3Schools has more information on using these events: onkeydown and onkeyup.
Also, I think I should note that there are some discrepancies across browsers in regards to the event properties (like, for example, in Firefox, you're supposed to access the keycode through event.which, while in IE it's event.keyCode, although Firefox may support event.keycode—confusing, isn't it?). Due to that, I'd recommend doing this stuff through a JavaScript framework, such as Prototype or jQuery, as they take care of all the icky compatibility stuff for you.
Here is the source for an HTML page that uses jQuery and does what htw's solution does.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Hijack Example</title>
<script type="text/javascript" src="../scripts/jquery-1.2.1.js">
</script>
<script type="text/javascript">
$(function(){
document.title = "before keypress detected";
$(document).keydown(function(event) {
// alert('stuff happened: ' + msg + " " + event.keyCode);
var keyChar = String.fromCharCode(event.keyCode).toLowerCase();
if (keyChar == "m" && event.ctrlKey) {
document.title = "ctrl-m pressed!";
}
});
});
</script>
</head>
<body id="body">
<p>Change the path to jquery above as needed (search for ../scripts/jquery-1.2.1.js)</p>
<p>Watch the title bar, then press control-M, then watch the title bar again!</p>
</body>
</html>
Hope this helps somebody!
Use the onkeydown or onkeyup event to fire a handler function:
var body = document.getElementsByTagName("body")[0];
body.onkeydown = function(event) {
var str = "";
for (var prop in event) {
str += prop + ": " + event[prop] + "<br>";
}
body.innerHTML = str;
};
With that you can see what properties an event object has.