jQuery on TAB pressure simulate on(mousedown) event - javascript

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!

Related

Is there an alternative to deprecated e.which in JavaScript?

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.

Restricting user from entering specific character in dynamically generated textboxes

I am trying to prevent user from entering two specific characters in any of the textboxes on the page. The code I am using does not work with dynamically appended textboxes.
DEMO
window.onload = function () {
$("input").keypress(function (e) {
if (e.which === 44 || e.which === 124) {//preventing , and |
e.preventDefault();
}
});
}
And since I am not using server controls I can not use ajax filter etc. I would like to have a simple solution to this. Without causing any conflicts in the code. Thank you.
Try to use event-delegation in this context, since you need to bind events for the elements which are being appended at the run time.
$(document).on('keypress',"input",function (e) {
if (e.which === 44 || e.which === 124) {
e.preventDefault();
}
});
Side Note: I just use document for delegating the event, but you should probably use any closest static parent to the input element, in order to attain a performance boos up.
use event delegation for dynamically created dom
$(document).on("keypress","input",function (e) {
if (e.which === 44 || e.which === 124) {
e.preventDefault();
}
});
document use immediate parent selector which is static in html
Demo: http://jsfiddle.net/4v78q/
http://jsfiddle.net/4v78q/1/
$(document).ready(function(){
$("input").each(function(){
$(this).keypress(function(e){
var keycode = e.which || e.keyCode;
if (keycode === 44 || keycode === 124) {
e.preventDefault();
}
});
});
});

How can I disable text selection using shift without disabling all text selection?

So I know this sounds like a duplicate, but it isn't (or if it is, the accepted answer on all the ones I can find doesn't work the way I need it to). The issue is this:
I'm writing in HTML5 using jQuery, I need to make a grid allow multi-select with control and shift. I have that logic working, but whenever you shift-click it selects the text in the grid. I want to prevent this selection, but here's the critical difference between this and the other questions I found: I want selection of text to work at all other times.
To restate: I want to disable text selection using shift WITHOUT disabling all text selection for the elements specified. Does anyone know how I can do that?
-- EDIT --
The following (in the constructor for the grid) solved this for me. As the answerer suggested, I declared a class for unselectability.
this.gridBody = $("#userGrid");
var handleKeydown = function(e)
{
e = e || window.event;
var keyPressed = e.keyCode || e.which;
if (keyPressed == keys.shift) {
e.data.gridBody.addClass("unselectable");
}
};
var handleKeyup = function(e)
{
e = e || window.event;
var keyPressed = e.keyCode || e.which;
if (keyPressed == keys.shift) {
e.data.gridBody.removeClass("unselectable");
}
};
$(document).on('keydown', this, handleKeydown);
$(document).on('keyup', this, handleKeyup);
That will bind on document an event where it disables text selection upon pressing DOWN shift
document.onkeydown = function(e) {
var keyPressed = e.keyCode;
if (keyPressed == 16) { //thats the keycode for shift
$('html').css({'-moz-user-select':'-moz-none',
'-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none',
'-webkit-user-select':'none',
'-ms-user-select':'none',
'user-select':'none'
}); //or you could pass these css rules into a class and add that class to html instead
document.onkeyup = function() {
//here you remove css rules that disable text selection
}
}
}
Hopefully i have helped you.
Based on comments
document.onkeydown = function(e) {
var keyPressed = e.keyCode;
if (keyPressed == 16) { //thats the keycode for shift
$('html').addClass('unselectable'); //unselectable contains aforementioned css rules
document.onkeyup = function() {
$('html').removeClass('unselectable'); //and simply remove unselectable class making text selection availabe
}
}
}
Another solution you might consider: instead of preventing text selection by watching for shift keys and toggling selectability, you could just clear the text selection.
window.getSelection().removeAllRanges();
I find this more convenient because it can be run in your click handler to "cancel" the default behavior. Appears to work in IE 9+ and other modern browsers.

Remove Any Spaces While Typing into a Textbox on a Web Page Part II

This involves HTML + JS and/or JQuery:
I would have commented on the previous post, but I don't have comment reputation or cannot comment for some reason.
Josh Stodola's great code from Part I is as follows:
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
This works great except .replace puts the cursor at the end of the string on every keyup (at least in IE8 and Chrome).
As a result, it renders the left & right cursor keys useless, which is needed inside the input box.
Is there any way to enhance the above code so that the cursor keys do not activate it, but so that the text still gets updated on the fly?
The best solution is to avoid using key events to capture text input. They're not the best tool for the job. Instead, you should use the HTML5 oninput event (supported in the latest and recent versions of every current major browser) and fall back to onpropertychange for older versions of Internet Explorer:
var alreadyHandled;
txt.bind("input propertychange", function (evt) {
// return if the value hasn't changed or we've already handled oninput
if (evt.type == "propertychange" && (window.event.propertyName != "value"
|| alreadyHandled)) {
alreadyHandled = false;
return;
}
alreadyHandled = true;
// Your code here
});
These events don't fire for keys that don't result in text entry — don't you just hate it when you shift-tab back to a form element and the resulting keyup event causes the page's script to move focus forward again?
Additional benefits over key events:
They fire immediately when the key is pressed and not when the key is lifted, as in keyup. This means you don't get a visual delay before any adjustments to the text are made.
They capture other forms of text input like dragging & droppping, spell checker corrections and cut/pasting.
Further reading at Effectively detecting user input in JavaScript.
Update the function:
var func = function(e) {
if(e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40){
txt.val(txt.val().replace(/\s/g, ''));
}
}
try:
$(function() {
var txt = $("#myTextbox");
var func = function(e) {
if(e.keyCode != "37" && e.keyCode != "38" && e.keyCode != "39" && e.keyCode != "40"){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(function(evt){
if(evt.keyCode < 37 || evt.keyCode > 40) {
func;
}
}).blur(func);
});
Something like that should do it. It will run the function if the keycode isn't 37,38,39 or 40 (the four arrow key keycodes). Note that it won't actually stop the cursor position moving to the end when any other key is pressed. For that, you'd need to keep track of the current cursor position. Take a look at this link for jCaret plugin, which can do this

How can I disabling backspace key press on all browsers?

I'm trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backing out of an order. I have it working fine in most browsers, but in IE (testing in IE9, both regular and compatibility mode) it still allows the user to hit the backspace and go to the previous page.
Here's the code:
$(document).keypress(function(e){
var activeNodeName=document.activeElement.nodeName;
var activeElType=document.activeElement.type;
if (e.keyCode==8 && activeNodeName != 'INPUT' && activeNodeName != 'TEXTAREA'){
return false;
} else {
if (e.keyCode==8 && activeNodeName=='INPUT' && activeElType != 'TEXT' && activeElType != 'text'){
return false;
}
}
});
Any advice on what I'm doing wrong here?
Thanks!
I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.
$(document).keydown(function(e) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.which === 8) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.
Instead of keypress, try the keydown function, it will fire before the actual browser based hook. Also, putting in a preventDefault() function will assist in this. IE :
$(document).keydown(function(e){
e.preventDefault();
alert(e.keyCode);
});
Hope this helps.
The most Simple thing you can do is add the following one line in the very first script of you page at very first line
window.history.forward(1);
Most examples seem to be for the JQuery framework - Here an example for ExtJS
(I've been getting a lot of downvotes for this recently as the question now has JQuery tag on it, which it didn't previously. I can remove the answer if you like as isn't for JQuery but it's proven to help others not using that framework).
To use this add this code block to your code base, I recommend adding it inside the applications init function().
/**
* This disables the backspace key in all browsers by listening for it on the keydown press and completely
* preventing any actions if it is not which the event fired from is one of the extjs nodes that it should affect
*/
Ext.EventManager.on(window, 'keydown', function(e, t) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.getKey() == e.BACKSPACE) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Use e.which instead of e.keyCode; jQuery normalizes this value across browsers.
http://api.jquery.com/keydown/
To determine which key was pressed,
examine the event object that is
passed to the handler function. While
browsers use differing properties to
store this information, jQuery
normalizes the .which property so you
can reliably use it to retrieve the
key code.
Then, use e.preventDefault(); to prevent the default behaviour of moving to the previous page.
<html>
<head>
<script type="text/javascript">
function stopKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 8) && (node.type!="text")) {return false;}
}
document.onkeypress = stopKey;
</script>
</head>
<body onkeydown="return stopKey()">
<form>
<input type="TEXTAREA" name="var1" >
<input type="TEXT" name="var2" >
</form>
</body>
</html
I had to add the onDownKey attribute to the body in order to get editing keys to go to the functions.
$(document).keydown(function(e) {
var elid = $(document.activeElement).is('input');
if (e.keyCode === 8 && !elid) {
return false;
}
});
Hope this might help you
Seems like the "backspace" will also act as "navigation back" if you have selected radio buttons, check-boxes and body of document as well. Really annoying for forms - especially when using post. All the form could be lost with one slip of the "backspace" key -_- ...
Honestly... who's idea was it to allow the "backspace as a navigational "back" button!!! really bad idea in my opinion.
I disable the "backspace" default on anything that is not a text area or text field - like this:
$(document).keydown(function(e){
console.log(e.keyCode+"\n");
var typeName = e.target.type;//typeName should end up being things like 'text', 'textarea', 'radio', 'undefined' etc.
console.log(typeName+"\n");
// Prevent Backspace as navigation backbutton
if(e.keyCode == 8 && typeName != "text" && typeName != "textarea"){
console.log("Prevent Backbutton as Navigation Back"+typeName+"\n");
e.preventDefault();
}
//
})
Not sure where else one would want the normal behavior of a back-button other than in these two areas.
document.onkeydown = KeyPress;
function KeyPress(e) {
if (!e.metaKey){
e.preventDefault();
}
}

Categories