XUL textbox addEventListener - javascript

I'm trying to detect when a user hits escape or enter when in a xul textbox (firefox extension). But the following code doesn't seem to work. Any assistance would be much appreciated.
const KEY_ENTER = 13;
const KEY_ESCAPE = 27;
function keyPressed(e) {
switch (e.keyCode) {
case KEY_ENTER:
// do something
break;
case KEY_ESCAPE:
// do something
break;
}
}
var textbox = document.getElementById("mytextbox");
textbox.addEventListener('keypress', keyPressed, true);

Are you running this script before the textbox has been inserted in the document? This example works fine for me:
<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript"><![CDATA[
window.addEventListener("load", function() {
const KEY_ENTER = 13;
const KEY_ESCAPE = 27;
function keyPressed(e) {
switch (e.keyCode) {
case KEY_ENTER:
alert('enter');
break;
case KEY_ESCAPE:
alert('escape');
break;
default:
alert('default');
break;
}
}
var textbox = document.getElementById("mytextbox");
textbox.addEventListener('keypress', keyPressed, true);
alert('there');
}, false);
]]></script>
<textbox id="mytextbox" value="stuff"></textbox>
</window>
I'm also a little curious why you're passing true as the capturing argument when adding the listener. Generally you want to do stuff in the bubbling phase when handling events, not the capturing phase (i.e. after listeners on more-specific descendants of the element where you're listening have been called).

Related

Automatically click also 2nd button when click 1st button

I have problem in the click buttons. What i need is to automatically clicked 2nd button when i click the 1st button.. I have created a sample code which is not working
HTML
<button id="button1" class="btn btn-success">1st button</button>
<a id="button2" class="btn btn-success" href="google.com">2nd button</a>
jQuery
jQuery(document).ready(function() {
jQuery('#button1').click(function () {
jQuery('#button2').click();
})
});
Here's my jdfiddle
https://jsfiddle.net/wj8pb9sf/
I've had this code snippet for quite some time and it has proven itself to be very valuable in these situations:
// Simulate event
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style, you can drop this if you don't need to support IE8 and lower
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
It doesn't rely on jQuery and allowes you to simulate a bunch of usefull events. Simply do: fireEvent(document.getElementById('button2'), 'click');.
$("#button1").click(function(){
$("#button2").click();
});
And also you can't give href in button.

Quadratics: Replace Keyboard stroke for Mouse clicks

I am not advanced with Javascript. i was hoping for someone to simply explain the process to edit the following code.
this.hideNextButton();
this.hidePreviousButton();
var that = this;
Event.observe(document, 'keydown', function keydownCallback(e) {
var choiceID = null;
switch (e.keyCode) {
case 74: // 'j' was pressed
choiceID = 1;
break;
case 75: // 'k' was pressed
choiceID = 2;
break;
}
if (choiceID) {
Event.stopObserving(document, 'keydown', keydownCallback);
that.setChoiceValue(choiceID, true);
that.clickNextButton();
}
});
If a user wants to replace the click of a mouse with clicking a letter on the Keyboard, eg. Click J for the next question or to select yes, click A. I think that is what this code is doing but I'd like to pull it apart a bit to add or remove letters to complete additional tasks, such as next question etc.
Any help or pointing in the right direction is a help!
In the code you provided pressing 'j' or 'k' answers the current question by setting the choice value and goes to the next page. To add other keyboard presses you would additional cases to the switch using the appropriate keycode. For example, if you wanted 'j' to just go to the next page and 'a' to answer 'Yes', it would be something like this (remove the if(choiceID) section):
Event.observe(document, 'keydown', function keydownCallback(e) {
switch (e.keyCode) {
case 65: // 'a' was pressed
that.setChoiceValue(1, true);
break;
case 74: // 'j' was pressed
Event.stopObserving(document, 'keydown', keydownCallback);
that.clickNextButton();
}
});
You need to track pointed pointed element and call click event of pointed element when the key j is pressed.
var pointedElement;
document.onmousemove = function(e) {
pointedElement = e.srcElement;
}
document.onkeydown = function(e) {
switch (e.keyCode) {
case 74: // 'j' was pressed
pointedElement.click()
break;
}
}
Edit: My answer was just about the idea to change a click element in the whole window with another key but in your case you it is different. I can not help you by just looking this snippet but you need to change switch case block with the same functionality of buttons. What exactly those buttons are doing? You need to call the same functionality of next and previous keys are handling.

Trigger click event of plus button on google plus

I cant trigger event onClick of plus button in Google plus
I have try with a method:
But it didn't work.
The code I tried
$(".mUbCce.fKz70d.GsLz7c.teCjMb.M9Bg4d").click()
I also noticed that when my mouse over the plus button, the mouse icon change to "hand-icon" but, I didn't find any CSS cursor for it.
Is there any magic from google ?
Thanks
Try this: Define a function fireEvent() like this:
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
var bubbles = eventName == "change" ? false : true;
event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
And call
fireEvent($0,"mousedown")
fireEvent($0,"mouseup")
with $0 is the element you want to click

How to get the focus of the elements in javascript using keyarrows

My html contains list of elements. I want to use the arrow keys to select the elements.
Here is my Code: [http://jsfiddle.net/T8S7c/]
What I want is on preesing the keys the focus needs to be in the selected element like hover effects.( For example if I press the down key for the first time Ambaji has to be in focus)
I know the code of the key event but i dont know how to get the focus on the keypress.
Can anyone help me in this
My strategy for solving this would be to specify an order of focus through an array of the links, as well as having some variable specifying which link should be in focus.
var order = new Array("l1", "l2", "l3", "l4");
var current = -1;
function updateCurrent(inc) {
current = (current + inc) % order.length;
current = Math.max(current, 0);
}
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 38:
updateCurrent(-1);
document.getElementById(order[current]).focus();
break;
case 40:
updateCurrent(1);
document.getElementById(order[current]).focus();
}
};
Updated your script. Have a look at this. Fiddle : http://jsfiddle.net/T8S7c/6/
var myLinks = document.getElementsByTagName("a");
var myLinksIndex = 0;
myLinks[myLinksIndex].focus();
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 38: // Up arrow
if(myLinksIndex > 0){myLinks[-- myLinksIndex].focus();}
break;
case 40:// Down arrow
if(myLinksIndex < myLinks.length){myLinks[++ myLinksIndex].focus();}
break;
}
};

JavaScript key listener disabled when inside a text form

I have a key listener assigned to the arrow keys to navigate a slideshow. But I want to disable the key listener, temporarily, while a user is typing inside an input field. How can I do that? My current code looks like this:
//Listen to the keys
function checkKey(e) {
switch (e.keyCode) {
case 37:
changeImage('prev');
break;
case 39:
changeImage('next');;
break;
}
}
if (jQuery.browser.mozilla) {
jQuery(document).keypress (checkKey);
} else {
jQuery(document).keydown (checkKey);
}
First, there's no need for the browser check. For checking arrow keys, just use the keydown event for all keys.
Second, I suggest (as Sean Hogan did) checking the target of the event before doing the slideshow stuff. The following will work on all mainstream desktop browsers:
document.body.onkeydown = function(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
var targetTagName = (target.nodeType == 1) ? target.nodeName.toUpperCase() : "";
if ( !/INPUT|SELECT|TEXTAREA/.test(targetTagName) ) {
switch (evt.keyCode) {
case 37:
changeImage('prev');
break;
case 39:
changeImage('next');
break;
}
}
}
A bit ugly, but should work:
var moz = jQuery.browser.mozilla;
if (moz) {
jQuery(document).keypress(checkKey);
} else {
jQuery(document).keydown(checkKey);
}
jQuery("#myInput").focus(function() {
if (moz) {
jQuery(document).unbind("keypress");
} else {
jQuery(document).unbind("keydown");
}
}).blur(function() {
if (moz) {
jQuery(document).keypress(checkKey);
} else {
jQuery(document).keydown(checkKey);
}
});
If the focus is on an input element then that element will be the target for key events.
So you could just do a check on event.target.tagName.
e.g.
function checkKey(e) {
switch (e.target.tagName) {
case "INPUT": case "SELECT": case "TEXTAREA": return;
}
// rest of your handler goes here ...
}
Add onfocus and onblur event to the input field and set a global variable value. Check for that global variable in the begining of your checkKey event handler.
<input type="textbox" onfocus="window.inTextBox = true;" onblur="window.inTextBox = false;" />
function checkKey(e) {
if (!window.inTextBox)
{
...
}
}
I really like the simplicity of Ilya Volodin's suggestion, but I would set the event handler in the script and not embed it into the html:
var textFocus = false;
$("textbox").focus(function() {
textFocus = true;
});
$("textbox").blur(function() {
textFocus = false;
});
function navKeys() {
if (textFocus) {
return false;
} else {
......
}
}
This would be even simpler if jquery had :focus as a selector.
function navKeys() {
if ($("textbox:focus") {
return false;
} else {
......
}
}
But that is just hypothetical code at this point.

Categories

Resources