Getting keypresses in javascript - javascript

I need some help getting keyboard presses. I want to build a function to return the currently pressed key. How could this be done?
Many thanks.

Yes it can done or even you can do more with the following
http://www.openjs.com/scripts/events/keyboard_shortcuts/
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="./pages/scripts/jsl.js"></script>
<script type="text/javascript" src="./pages/scripts/common.js"></script>
<script type="text/javascript" src="./pages/scripts/shortcuts_v1.js"></script>
<script type="text/javascript">
function init() {
shortcut("Shift+F1",function(event) {
alert("Help Me!");
event.preventDefault();
});
shortcut("Ctrl+S",function(event) {
alert("Saved!");
event.preventDefault();
});
shortcut("Right",function(event) {
alert("Right");
event.preventDefault();
});
}
addEvent(window,'load',init);
//ie workaround
document.onfocusout = function(e){
if( e === undefined ){//ie
var evt = event;//ie uses event
if( evt.toElement == null ){//check where focus was lost to
document.getElementById('status').innerHTML += "document.onfocusout->lost<br>";
}
}
};
//ie workaround
document.onfocusin = function(e){
if( e === undefined ){//ie
var evt = event;//ie uses event
if( evt.toElement == null ){//check where focus was lost to
document.getElementById('status').innerHTML += "document.onfocusout->gained<br>";
}
}
};
window.onblur = function(e){
if( e !== undefined ){//ie will have an undefined e here, so this screens them out
document.getElementById('status').innerHTML += "window.onblur->lost<br>";
}
};
window.onfocus = function(e){
if( e !== undefined ){//ie will have an undefined e here, so this screens them out
document.getElementById('status').innerHTML += "window.onblur->gained<br>";
}
};
</script>
</head>
<body>
<div id="status"></div>
</body>
</html>

http://www.w3schools.com/tags/ref_keyboardshortcuts.asp
http://www.openjs.com/scripts/events/keyboard_shortcuts/
http://selfcontained.us/2009/09/16/getting-keycode-values-in-javascript/
refer these links . Is it like you want all the keyboardshortcuts to be returned or some basic functionalities....??

Related

Does not get the DOM elements inside of iframe until I inspect element to that particular tag

I have the below webpage which embeds a chatbot window into it.
https://lippert-web.firebaseapp.com/
I'm trying to change the bot name under a certain condition(for which I'm using an event of the bot framework).
<!DOCTYPE html>
<html>
<head>
<title>Web Channel</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"
/>
</head>
<body>
<script type="text/javascript">
var AvaamoChatBot = function (t) {
function o(t, o) {
var n = document.createElement("script");
n.setAttribute("src", t),
n.setAttribute("id", "avm-web-channel"),
(n.onload = o),
document.body.appendChild(n);
}
return (
(this.options = t || {}),
(this.load = function (t) {
o(this.options.url, function () {
window.Avaamo.addFrame(),
t && "function" == typeof t && t(window.Avaamo);
});
}),
this
);
};
var chatBox = new AvaamoChatBot({
url:
"https://c10.avaamo.com/web_channels/t-dae9bf37-e942-44ac-bb42-3804c81bde36?action=demo&banner=true&banner_text=+&banner_title=This+is+how+the+chat+agent+shows+up&controller=web_channels&demo=true&theme=avm-messenger",
});
chatBox.load(function (avaamo) {
avaamo.onBotMessage = (message) => {
if(message.content && message.content.toLowerCase().includes("sure thing, i’ll get you right") && message.conversation_uuid){
console.log("Live Agent Transfer");
document.querySelectorAll('*[id^="name-"]').forEach(botName=>{
botName.innerHTML = "Live Agent";
});
}
else if(((message.content && message.content.toLowerCase().includes("i'm sorry, but no customer care specialist") ||(avaamo.content_type == "default_card" && avaamo.attachments.default_card.description.toLowerCase().includes("thanks for chatting with us today"))) && message.conversation_uuid)){
console.log("Out Of Live Agent");
document.querySelectorAll('*[id^="name-"]').forEach(botName=>{
botName.innerHTML = "Valerie";
});
}
};
});
//chec
// if(!window.Avaamo){
// setTimeout(function (){
// Avaamo.welcomeNotification.open();
// },1000)
// }
</script>
</body>
</html>
Here I'm using the below code to change the innerHtml, which doesn't seems to be working:
document.querySelectorAll('*[id^="name-"]').forEach(botName=>{
botName.innerHTML = "Valerie";
});
Also when I inspect element, open the bot window and 1st try the code, I get no result.
document.querySelectorAll('*[id^="name-"]')
But then I inspect into botname element, and try it works.
Just want to understand the why is this happening.

issues with html and js

This is so bloody frustrating. I went through W2school tutorials, where bits and pieces are presented to you but it does not answer how to put it all together. I thought I understood it but when I put it into practice, nothing. Firebug is telling me that inputEmp() is not defined, but is quite obviously defined in the .js file. Can someone please tell me what minor detail I left out? Thanks First the Html, then the .js file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/payroll.css" />
<title>Payroll System</title>
<script type="text/javascript" src="scripts/payroll.js"></script>
<script type="text/javascript" >
var emps = new Array();
</script>
</head>
<body>
<h1>Jackson Payroll System</h1>
<button type="button" onclick="inputEmp()">
Click here to enter employees
</button>
</body>
</html>
// payroll.js
function inputEmp() {
var inName = "";
var loopCt = 0
var tArray = new Array();
while (inName != "-1}
{
prompt inName = prompt("Please enter your name (enter -1 to finish)",
"Employee Name");
if (inName == "-1") { break; }
if (inName==null || inName=="")
{
alert("Blank names are not allowed. To exit enter '-1'.");
}
else
tArray[loopCt++] = inName;
{
}
return tArray;
}
Yes, you forgot to close the brace { of while loop before return statement. and the quotes is not closed in condition.
Try this
function inputEmp() {
var inName = "";
var loopCt = 0
var tArray = new Array();
while (inName != "-1"} {
prompt inName = prompt("Please enter your name (enter -1 to finish)","Employee Name");
if (inName == "-1") { break; }
if (inName==null || inName=="")
{
alert("Blank names are not allowed. To exit enter '-1'.");
}
else
tArray[loopCt++] = inName;
{
}
}
return tArray;
}
There is a lot of problem in your code:
var loopCt = 0 should look like this var loopCt = 0;
while (inName != "-1} should look like this while (inName != "-1)
prompt inName = prompt... should look like this inName = prompt...
There is an empty { } under the else statement
Here is a jsfiddle that shows you the corrected code.

Code works in chrome and firefox but fails in IE9

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function abc()
{
ansArray = ['a'];
document.write('<input type = "button" value = "a">');
document.write('<input type = "button" value = "b">');
var myButton = document.getElementsByTagName("input");
myButton[0].onclick = function() {
if(ansArray[0] == 'a')
myButton[0].style.backgroundColor = "green";
else
myButton[0].style.backgroundColor = "red";
}
myButton[1].onclick = function() {
if(ansArray[0] == 'b')
myButton[1].style.backgroundColor = "green";
else
myButton[1].style.backgroundColor = "red";
}
}
</script>
</head>
<body onload="abc()">
</body>
</html>
This code segment is to change the colour of the two buttons on click event,works fine in chrome and firefox but the onclick functions does not work in IE9. Please help... Thanks in advance
Try calling the function like
(function abc(){
// code here
})();
Also use ; after each function expression, i.e. myButton[0].onclick = function() {...};.
Working here.

Chrome Browser Issue for Button

I have an issue with a Button. It is appearing in IE and Firefox, but not appearing in Chrome.
The code for the button is using Rally API and it’s generated while loading the page.
I have tried Googling the answer, but I couldn't find anything.
Heres my code:
function onClick(b, args) {
if(OneButtonClickFlag == true) {
OneButtonClickFlag = false;
var buttonValue = args.value;
var userName = "__USER_NAME__";
TimeSheetReport(); // calling the “timesheet report “
}
}
function onLoad() {
var config = {
text: "Generate",
value: "myValue"
};
var button = new rally.sdk.ui.basic.Button(config);
button.display("buttonDiv", onClick); // call the “onclick” function
}
rally.addOnLoad(onLoad);
This App below seems to work with your code in it up until the point where it encounters your OneButtonClick flag. I tested it in Chrome. Does this work for you?
<head>
<title>Button Example</title>
<meta name="Name" content="Component Example: Button"
/>
<meta name="Version" content="2010.4" />
<meta name="Vendor" content="Rally Software" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.26/sdk.js"></script>
<script type="text/javascript">
function onClick(b, args) {
console.log("works until this undefined variable");
if (OneButtonClickFlag == true) {
OneButtonClickFlag = false;
var buttonValue = args.value;
var userName = "__USER_NAME__";
TimeSheetReport(); // calling the “timesheet report “
}
}
function onLoad() {
var config = {
text: "Generate",
value: "myValue"
};
var button = new rally.sdk.ui.basic.Button(config);
button.display("buttonDiv", onClick); // call the “onclick” function
}
rally.addOnLoad(onLoad);
</script>
</head>
<body>
<div id="buttonDiv"></div>
</body>

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources