Im new to JavaScript event handling, I would like to trigger an event upon mousemove and left-click on a div element. My current implementation is to check that e.which == 1 when I trigger the mousemove event function. However, I have read that the e.which property is now deprecated (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which). My code:
div.addEventListener("mousemove", myEventFunction)
function myEventFunction(e){
if (e.which == 1){
//do something
}
}
Is there any alternative to perform this operation?
You can use event.button if it is gonna be a mouse event.
The MouseEvent.button read-only property indicates which button was pressed on the mouse to trigger the event.
function myEventFunction(e) {
e = e || window.event;
if ("buttons" in e) {
return button;
}
var button = e.which || e.button;
return button;
}
The above function returns the button value.
Related
I want to run a method whenever the ESC button gets clicked. In the onkeypress Event documentation I read that i will have to use keydown
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.
I managed to write a working example:
document.onkeydown = function (e) {
if (document.getElementById("fullscreen") !== null) {
var key = e.which || e.keyCode;
if (key === 27) {
alert(1);
}
}
}
<div id="fullscreen">test</div>
The event listeners in our project have a different pattern, so I tried rewrite it in the same pattern but the code isn't reacting on the key press.
document.getElementById("fullscreen").addEventListener("keydown",
function (e) {
var key = e.which || e.keyCode;
if (key === 27) {
alert(1);
}
});
<div id="fullscreen">test</div>
Why isn't the second code snippet reacting on the key press like the first snippet?
In my webpage i have to trap TAB key pressure and then simulate mousedown event for the object involved.
I tried so:
$('*').keydown(function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
var elementClicked = e.target.nodeName;
elementClicked.mousedown();
}
});
but error
Uncaught TypeError: undefined is not a function
on elementClicked.mousedown(); row appears.
How can i simulate and call the mousedown event on element involved in TAB pressure??
Thanks in advance
AM
$(this).trigger('mousedown') or just $(this).click() and this will trigger whatever event is bound to that element. note that you should do *... that's super bad for performance.
Try:
$(document).on('keydown.tab', '*', function(e){
if( e.keyCode == 9 ){
$(this).trigger('mousedown');
}
return false;
});
But you can't really know on which element was the TAB clicked...
UPDATE:
you should first give all elements the attribute tabindex, only then those element could be tracked when pressing the tab key, because they have focus (by clicking on them first or focusing via keyboard) :
$('body *').each(function(i){
this.setAttribute('tabindex',i);
});
DEMO PAGE - only the h1 element simulates click using TAB
elementClicked is an object name and not an object -
select object using jquery:
$(elementClicked).mousedown()
May be you should try below updated code:
$(document).on("keyup", function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
var elementClicked = $(this);
elementClicked.trigger("mousedown");
}
});
Hope this helps!
I am overriding the behavior of the space bar and arrow keys when an element is focused to provide keyboard support on a web page. I need to disable the default behavior of those keys, which is to scroll the web page. I thought all that was needed to do this was to return false when you handled the event, but that didn't do the trick. I also added preventDefault yet it still scrolls the page in addition to performing my custom actions. What is the problem here?
document.getElementById('someID').onkeyup = function(e) {
var keyCode = e.which || e.keyCode;
var handled = false;
if (keyCode == 38 || keyCode == 40) { //up or down arrow
//do something fun
e.preventDefault();
handled = true;
}
return !handled; //return false if the event was handled
}
Change the event to onkeydown. By the time you reach onkeyup it's too late and the scrolling has already changed.
document.getElementById('someID').onkeydown = function(e) {
var keyCode = e.which || e.keyCode;
var handled = false;
if (keyCode == 38 || keyCode == 40) { //up or down arrow
//do something fun
e.preventDefault();
handled = true;
}
return !handled; //return false if the event was handled
}
For whatever reason I can't capture "SHIFT+TAB" combination.
I am using the latest jQuery.
Same result if I use other ajax/javascript, etc.
Here is a simple example that should work as I currently understand it...
event.which or event.KeyCode are always "undefined" only shiftKey exists in a scenario involving a "SHIFT+TAB" or backward keyboard traversal, traditionally inherent in windows based apps/web or otherwise...
function ShiftTab()
{
debugger;
if(event.KeyCode == 9 && event.shiftKey) // neither this line nor the following work
// if (event.which == 9 && event.shiftKey) // shift + tab, traverse backwards, using keyboard
{
return true;
}
else
{
return false;
}
}
this seems to be yet another item related to tab order that no longer works as it traditionally worked in Microsoft.Net WinForm/WebForm based apps.
If you are using jQuery, this should be how the code is working. Make sure keyCode is lower case. Also, jQuery normalizes keyCode into which:
$(document).keyup(function (e) {
if (e.which === 9 && e.shiftKey) {
ShiftTab();
}
});
If you're into terse JavaScript:
$(document).keyup(function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
jQuery 1.7+ on syntax:
$(document).on('keyup', function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
I created a function which I wired up to my button's onkeydown event. I used onkeydown, because onkeypress would not capture my tab key press
function ShiftTab(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode; // for trans-browser compatibility
if (charCode === 9) {
if (e.shiftKey) {
$('#controlName').focus();
return false;
} else {
return true;
}
}
I took this approach to deal with two specific problems:
onkeypress would not capture tab key press
When click shift-tab, shift key press would trigger function, so I had nest the shiftkey modifier check
use same code inside keypress event.
the tab changes the element between keypress and keyup.
here we get event.key = tab and event.shiftKey = true.
I have multiple fields, typically enter will be pressed on one of the two main ones. I want to know which field enter has been pressed on, how do i do this? (i dont know much JS)
its simple to add an "onkeypress" event to each of the fields, and then in the event handler to examine the keycode that is attached to the event. For example, consider the following code:
form.elements['fieldone'].onkeypress = function(evt) {
if (window.event) evt = window.event; // support IE
if (evt.keyCode == 13) alert("Enter was pressed!");
return true;
}
Please note that under most browsers, pressing ENTER in a form field would post that form. If you don't want that to happen, you can simply return false from the onkeypress handler and that would tell the browser to ignore that key.
Check for enter and set some hidden field (example uses JQuery):
$('#input_text').keyup(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
alert('Enter key was pressed.');
}
});
Include this in your page, it should fire automatically when you hit any key and tell you which html element had focus when it happened.
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event;
f ((e.charCode) && (e.keyCode == 13))
alert('Yay! Enter was pressed while field ' + document.activeElement.id + ' had focus!');
}
</script>
You can check from which element the event bubbled from using something like the following
var text1 = document.getElementById('text1');
var text2 = document.getElementById('text2');
text1.onkeypress = keyPresser;
text2.onkeypress = keyPresser;
function keyPresser(e) {
// to support IE event model
var e = e || window.event;
var originalElement = e.srcElement || e.originalTarget;
if (e.keyCode === 13) {
alert(originalElement.id);
}
}
Here's a Working Demo
I would recommend taking a look at the differences in Browser event models and also at unobtrusive JavaScript .
QuirksMode - Introduction to Events
The IE Event Model
Pro JavaScript Techniques - Unobtrusive Event Binding
Use event delegation to avoid attaching event handlers to a large number of elements:
window.onload = function () {
document.onkeyup = function (e) {
e = e || window.event;
var target = e.target || e.srcElement,
keyCode = e.keyCode || e.which;
if (target.tagName.toLowerCase() == 'input' && keyCode == 13) {
alert('Enter pressed on ' + target.id);
}
};
};