I'm using contenteditable on my website (and JS/JQuery). I have a limit (maxlength) of 160 letters in it. When it comes to 160, function addOnTypeKeyDown() fires (when typing) e.preventDefault(), but this function prevent Ctrl+C, prevent mouse selection, prevent Ctrl+A as long as I click backspace (so e.preventDefault() isn't working).
My question is how can I "switch on" options like above (Ctrl+C and so on...) without letting user type letters.
I know that I can use input or textarea, but I'm asking how can I solve this problem using contenteditable?
I used e.which for Ctrl+C and mouse events, but that didn't work.
Function looks like that:
function addOnTypeKeyDown(event){
var cntMaxLength = parseInt($(this).attr('maxlength'));
event = event || window.event;
if ($(this).text().length >= cntMaxLength) {
if(!(event.which==8))
{
event.preventDefault();
$(this).parent().find("#error").css("display", "block");
}
}
else{
$(this).parent().find("#error").css("display", "none");
}
}
Thanks for your time and effort.
Related
I'm trying to build a functionality that allows keyboard tabbing between two buttons (CodePen below). More specifically I would like the user to be able to tab onto "button1" and on tab, jump to "button2" and then on tab jump back to button 1.
My solution is to put an event listener on "button1" and listen for a tab keyboard event. When that is triggered, use JQuery's focus() method to shift focus to "button2". On "button2" there is an identical listener that listens for tab event and shift focus back to "button1".
The problem is that when I tab onto "button1", the listener records focus and tab event and shift focus onto "button2" which in turn records focus and tab event and shift it back to "button1" again, creating an infinite loop.
Could I please get suggestions in how to solve this problem?
The real world application of this would be to restrict tabbing within a specific module or section of a page.
Thanks!
Steve
https://codepen.io/steveliu7/pen/WOoMJY
var $button1 = $('.b1');
var $button2 = $('.b2');
var checkButton = function(event) {
if ($button1.is(':focus') && event.which === 9){
console.log($(this))
$('.b2').focus();
return;
};
if ($button2.is(':focus') && event.which === 9){
console.log($(this))
$('.b1').focus();
return;
};
}
$('button').on('keydown', checkButton);
You want to restrict tab navigation between two buttons.
Note that it won't restrict screenreaders navigation to those two buttons.
You have to consider TAB navigation but also SHIFT+TAB navigation
On a purely technical point of view event.preventDefault() is what your are searching for:
var checkButton = function(event) {
if (event.which === 9) {
if ($button1.is(':focus')) {
$button2.focus();
event.preventDefault();
} else if ($button2.is(':focus')){
$button1.focus();
event.preventDefault();
}
}
}
I think what you are trying to do can be achieved much easier with the tabindex property in HTML. If you want to restrict tabbing to certain elements only, you can set tabindex="-1" for those elements that you do not want focused.
Source: https://www.w3schools.com/tags/att_global_tabindex.asp
I have a button with an anchor, that I would like to trigger with the spacebar for accessibility reasons. Instead, clicking the spacebar jumps the page down when button is in focus.
Go to Stack Overflow
I have tried eating the spacebar key:
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
but of course this is not what I want. I'm not sure if mapping the spacebar key to the enter key is a smart solution, or if its possible. How can I trigger a button with the spacebar using pure JS?
You might want to look into a prevent default solution:
window.onkeydown = function(event){
if(event.keyCode === 32) {
event.preventDefault();
document.querySelector('a').click(); //This will trigger a click on the first <a> element.
}
};
That will stop the space bar from performing the default action (to send a space) and then you can add your scroll to command below that inside the function.
Give your a link an id and try this:
var link = document.getElementById("link");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
link.click();
}
};
I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?
I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode
This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.
The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo
This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo
This question already has answers here:
Pressing spacebar scrolls page down?
(3 answers)
Closed 9 years ago.
I want to disable the scroll down when i pressed the spacebar. This only happens in firefox.
I already use overflow:hidden and meta tag viewport.
Thanks.
This should do the trick. It states that when the spacebar is pressed on the page/document it doesn't just prevent its default behavior, but reverts back to original state.
return false seems to include preventDefault. Source
Check JQuery API's for more information about keydown events - http://api.jquery.com/keydown/
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
JQuery example
$(document).keydown(function(e) {
if (e.which == 32) {
return false;
}
});
EDIT:
As #amber-de-black stated "the above code will block pressing space key on HTML inputs". To fix this you e.target where exactly you want spacebar blocked. This can prevent the spacebar blocking other elements like HTML inputs.
In this case we specify the spacebar along with the body target. This will prevent inputs being blocked.
window.onkeydown = function(e) {
if (e.keyCode == 32 && e.target == document.body) {
e.preventDefault();
}
};
NOTE: If you're using JQuery use e.which instead of e.keyCode Source.
The event.which property normalizes event.keyCode and event.charCode
JQuery acts as a normalizer for a variety of events. If that comes to a surprise to anyone reading this. I recommend reading their Event Object documentation.
Detect if the spacebar is being pressed. If it is, then prevent its default behaviour.
document.documentElement.addEventListener('keydown', function (e) {
if ( ( e.keycode || e.which ) == 32) {
e.preventDefault();
}
}, false);
Have you tried capturing the keydown event in javascript? If you are using jQuery you can read more about capturing key events here:
http://api.jquery.com/keydown/
If you aren't you can capture and ignore the space bar keypress as described here:
https://stackoverflow.com/a/2343597/1019092
I have currently an eventlistener listening for when a user enters an email address in a textbox on an html website. It then displays an alert when it detects an email address is being entered. Currently I have set it up whereby it detects the event blur then checks whether it meets the regex then an alert will display. This creates many alerts and is not very accurate as the alert
I need the eventlistener to listen for when the tab key specifically is pressed. I know I need to use KeyCodes but have not used them before. This eventlistener is currently working dynamically as it is a Firefox AddOn that scans a webpage so the eventlistener is not specifically attached to a specific input box.
Code:
vrs_getWin.document.getElementsByTagName("body")[0].innerHTML = bodyContents;
var inputFields = vrs_getWin.document.getElementsByTagName("input");
for(inputC=0; inputC < inputFields.length; inputC++) {
var elementT = inputFields[inputC].getAttribute("id");
inputFields[inputC].addEventListener("blur", function(){
var emailPattern = /(\w[-._\w]*\w#\w[-._\w]*\w\.\w{2,3})/g;
var resultEmail = emailPattern.test(vrs_getWin.document.getElementById(elementT).value);
if(result) {
prompts.alert(null, "Test", vrs_getWin.document.getElementById(elementT).value);
}
}, false);
}
Any help with this will be much appreciated.
I think from a UX stand point, I would not recommend using a javascript alert to notify the user of a problem, especially if you want the notification to happen when they have completed a single form input. The blur event would be my recommendation, and use some other visual cue to notify the user.
But, if you want to go with the tab key, the event your looking for is 'keydown', or 'keyup'. To use it you listen for the keydown event then check if the event.keyCode == '9'. (tab key)
document.addEventListener('keydown', function(e){
if( e.keyCode == '9' ){
alert('You pressed the tab key.');
}
}, false);
To get the keycodes of keys I like to pop open a console and type in:
document.addEventListener('keydown', function(e){
console.log( e.keyCode );
}, false);
Then when you press a key, it will output the keycode for that key.