http://codepen.io/anon/pen/rhnuE
I'm using JS Hotkeys from - https://github.com/jeresig/jquery.hotkeys
What I'm trying to do is deselect/focusout a focused contenteditable element. I also want the default focus dotted line to be removed when you click out of the element all called from the [Esc] key when pressed.
If anyone can help it'd be greatly appreciated.
$(document).ready(function() {
// Shortcut to deselect element
$(document).bind('keydown', 'esc', function() {
$('.box').focusout();
});
});
Try using
$('.box').blur()
instead of foucusout() it works fine for me.
$(document).ready(function() {
$(document).keyup(function(e) {
if (e.keyCode == 27) { // Key 27 is the same as Esc
$('#formId').blur();
}
});
});
Related
I've a simple form with a text input and a button disabled, this button can be enabled if i write on input text, keyup() is the best way but when i use right click and paste this event isn't called and doesn't trigger that event. So i tried event change(), it's work but not immediately, i must unfocus the input text for have the button enabled. How can i enable this button immediately with copy and paste?
$(document).ready(function () {
$('#id_input').bind('keyup paste click', function () {
if ($('#id_input').val().length === 6 ){
$('#btnSubmit').removeAttr('disabled');
}
else
$('#btnSubmit').attr('disabled', 'disabled');
});
});
Rory is right that your code should work in general especially if you paste using Ctrl + V.
I assume that you experience the issue only if you paste using right-click and then select Paste from the context menu.
Try to monitor the property changes:
$(document).ready(function() {
$('#id_input').bind('input propertychange', function() {
if ($('#id_input').val().length === 6) {
$('#btnSubmit').removeAttr('disabled');
} else
$('#btnSubmit').attr('disabled', 'disabled');
});
});
You need to use the onpaste event.
$(document).ready(function () {
$('#id_input').bind('keyup onpaste click', function () {
if ($('#id_input').val().length === 6 ){
$('#btnSubmit').removeAttr('disabled');
} else {
$('#btnSubmit').attr('disabled', 'disabled');
}
});
});
on a web page how do you enable the user to light up the boxes/items on the page using a specific key on your keyboard? eg. i want M to light up my title and when i press M again it turns it off?
this is what i have so far but feel like it could be cleaned up a lot
$('#abutton').click(function() {
$('#abutton').removeClass('off').addClass('on');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});
$('#bbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('off').addClass('on');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});
$('#cbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('off').addClass('on');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});
$('#dbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('off').addClass('on');
window.scrollTo(0,0);
});
Just add the general class .button to all of them. Then remove on from all .button elements and add on class to exact clicked element.
$('.button').click(function() {
$('.button').removeClass('on').addClass('off');
$(this).removeClass('off').addClass('on');
window.scrollTo(0,0);
});
You need to add addEventListener to your code and check inside it if the pressed key has keyCode you're expecting to do some action. Look on example below:
addEventListener("keydown", (event) => {
if (event.keyCode === '13')
//light on/off
});
Please check docs for more details
EDIT: jQuery also has its keyboard events
I'd like to be able to use the arrow keys to get to the select2 option I want and then press tab to select that option and then tab to the next element as usual.
I already got the down arrow to open the select2 with the following:
$(document).on('keydown', '.select2', function(e) {
if (e.originalEvent && e.which == 40) {
e.preventDefault();
$(this).siblings('select').select2('open');
}
});
And I can also use the arrows to get where I need to go. Now I'm struggling to make the tab part work.
I'm assuming since the select2-search__field has focus at the time I'm pressing the key, that that is the element I bind the event to? And then presumably I need to get the value of the currently highlighted option and trigger the select2 change?
I'm not 100% sure this is the right approach but I can't quite figure it out.
To achieve this you can use selectOnClose: true:
$(document).on('keydown', '.select2', function(e) {
if (e.originalEvent && e.which == 40) {
e.preventDefault();
$(this).siblings('select').select2('open');
}
});
$('select').select2({
selectOnClose: true
});
select {
min-width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
<select>
<option>AAAAA</option>
<option>BBBB</option>
<option>CCCC</option>
<option>DDDD</option>
<option>EEEE</option>
<option>FFFF</option>
<option>GGGG</option>
</select>
Just add following line in your code.
$(document).on("select2:close", '.select2-hidden-accessible', function () { $(this).focus(); });
Your issue will be resolved.
I had this same issue. Because selectOnClose: true also means that pressing Esc or clicking outside of the select dropdown was selecting the input, I have opted for a far more complicated and less elegant solution than the accepted answer. My solution has solved this issue for me (and allows subsequent tabbing to switch focus on down the DOM).
I added a listener to select2:closing (which fires immediately before it closes and thus when the highlighted li is still highlighted). Select2 gives that li an id that contains the value of the option to which it's tied. I parse that out and squirrel it away in state (I'm using Vue):
$(this.subjectSelect2).on('select2:closing', () => {
var idArray = $(".select2-results__option--highlighted")[0].id.split("-");
var id = idArray[idArray.length - 1];
this.select2LastHighlighted = id;
})
I then added a listener for keydown, so that if tab is pressed, it takes that value from state, and updates the select2 to that value:
$(this.subjectSelect2).on('select2:open', () => {
$(".select2-search__field")
.on('keydown', (e) => {
if (e.key == 'Tab') {
this.subjectSelect2.val(this.select2LastHighlighted);
this.subjectSelect2.trigger('change');
}
})
})
I'd love to hear if someone has a more elegant way to do this!
In this demo, if you place your cursor in the first field and then tab out (without making any changes), the keyup event is fired on the second field. i.e., you are tabbing out of first field and into second field. Is this behavior correct? How can I prevent this from happening? Same applies to shift + tab.
Note:
a) I believe all other keys, printable and non-printable, trigger the keyup event on the first field.
b) The event isn't triggered at all if you keep the tab pressed until it moves out of both fields.
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function() {
$('#firstfield').keyup(function() {
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function() {
alert('Handler for secondfield .keyup() called.');
});
});
A key's default action is performed during the keydown event, so, naturally, by the time keyup propagates, the Tab key has changed the focus to the next field.
You can use:
jQuery(document).ready(function() {
$('#firstfield, #secondfield').on({
"keydown": function(e) {
if (e.which == 9) {
alert("TAB key for " + $(this).attr("id") + " .keydown() called.");
}
},
"keyup": function(e) {
if (e.which != 9) {
alert("Handler for " + $(this).attr("id") + " .keyup() called.");
}
}
});
});
This way, if the Tab key is pressed, you can make any necessary adjustments before handling other keys. See your updated fiddle for an exampe.
Edit
Based on your comment, I revamped the function. The JavaScript ended up being a bit complicated, but I'll do my best to explain. Follow along with the new demo here.
jQuery(document).ready(function() {
(function($) {
$.fn.keyAction = function(theKey) {
return this.each(function() {
if ($(this).hasClass("captureKeys")) {
alert("Handler for " + $(this).attr("id") + " .keyup() called with key "+ theKey + ".");
// KeyCode dependent statements go here.
}
});
};
})(jQuery);
$(".captureKeys").on("keydown", function(e) {
$("*").removeClass("focus");
$(this).addClass("focus");
});
$("body").on("keyup", "*:focus", function(e) {
if (e.which == 9) {
$(".focus.captureKeys").keyAction(e.which);
$("*").removeClass("focus");
}
else {
$(this).keyAction(e.which);
}
});
});
Basically, you give class="captureKeys" to any elements on which you want to monitor keypresses. Look at that second function first: When keydown is fired on one of your captureKeys elements, it's given a dummy class called focus. This is just to keep track of the most recent element to have the focus (I've given .focus a background in the demo as a visual aid). So, no matter what key is pressed, the current element it's pressed over is given the .focus class, as long as it also has .captureKeys.
Next, when keyup is fired anywhere (not just on .captureKeys elements), the function checks to see if it was a tab. If it was, then the focus has already moved on, and the custom .keyAction() function is called on whichever element was the last one to have focus (.focus). If it wasn't a tab, then .keyAction() is called on the current element (but, again, only if it has .captureKeys).
This should achieve the effect you want. You can use the variable theKey in the keyAction() function to keep track of which key was pressed, and act accordingly.
One main caveat to this: if a .captureKeys element is the last element in the DOM, pressing Tab will remove the focus from the document in most browsers, and the keyup event will never fire. This is why I added the dummy link at the bottom of the demo.
This provides a basic framework, so it's up to you to modify it to suit your needs. Hope it helps.
It is expected behavior. If we look at the series of events happening:
Press Tab Key while focus is on first text box
Trigger key down event on first text box
Move focus to second text box
Lift finger off tab key
Keyup event is triggered on second text box
Key up is fired for the second text box because that is where it occurs since the focus was shifted to that input.
You can't prevent this sequence of events from happening, but you could inspect the event to see what key was pressed, and call preventDefault() if it was the tab key.
I was recently dealing with this for a placeholder polyfill. I found that if you want to capture the keyup event in the originating field, you can listen to the keydown event and fire the keyup event if a tab was pressed.
Instead of this:
$(this).on({'keyup': function() {
//run code here
}
});
Change to this:
$(this).on({'keydown': function(e) {
// if tab key pressed - run keyup now
if (e.keyCode == 9) {
$(this).keyup();
e.preventDefault;
}
},
'keyup': function() {
//run code here
}
});
I ended up using this solution:
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function () {
$('#firstfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for secondfield .keyup() called.');
});
});
This solution doesn't run the alert if the key is tab, shift or both.
Solution: http://jsfiddle.net/KtSja/13/
I have a span element that I want to become editable upon double-click. (That is, the user can edit the text and it will save when s/he clicks outside.)
The effect I want to emulate is similar to when I double-click CSS properties in the Google Chrome Developer Tools. (See picture.)
Now tested, and does work (at least Firefox 8 and Chromium 14 on Ubuntu 11.04):
$('span').bind('dblclick',
function(){
$(this).attr('contentEditable',true);
});
JS Fiddle demo.
Edited in response to Randomblue's comment (below):
...how do I detect when the user clicks outside the span, so that I can set attr('contentEditable', false)
Just append the blur() method:
$('span').bind('dblclick', function() {
$(this).attr('contentEditable', true);
}).blur(
function() {
$(this).attr('contentEditable', false);
});
JS Fiddle demo.
If you want a solution that works in ALL modern browsers, here's a nifty little jQuery plugin I made that emulates the functionality you described:
SIMPLY DROP THIS BLOCK INTO YOUR CODE-BASE:
//plugin to make any element text editable
//http://stackoverflow.com/a/13866517/2343
$.fn.extend({
editable: function() {
var that = this,
$edittextbox = $('<input type="text"></input>').css('min-width', that.width()),
submitChanges = function() {
that.html($edittextbox.val());
that.show();
that.trigger('editsubmit', [that.html()]);
$(document).unbind('click', submitChanges);
$edittextbox.detach();
},
tempVal;
$edittextbox.click(function(event) {
event.stopPropagation();
});
that.dblclick(function(e) {
tempVal = that.html();
$edittextbox.val(tempVal).insertBefore(that).bind('keypress', function(e) {
if ($(this).val() !== '') {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}
});
that.hide();
$(document).click(submitChanges);
});
return that;
}
});
Now you can make any element editable simply by calling .editable() on a jQuery selector object, like so:
$('#YOURELEMENT').editable();
To get the changes after the user submits them, bind to the "editsubmit" event, like so:
$('#YOURELEMENT').editable().bind('editsubmit', function(event, val) {});
//The val param is the content that's being submitted.
Here's a fiddle demo: http://jsfiddle.net/adamb/Hbww2/
The above works: I've tested it in this jsfiddle: http://jsfiddle.net/nXXkw/
Also, to remove the editability when user clicks off of the element, include:
$('span').bind('blur',function(){
$(this).attr('contentEditable',false);
});
I found this nice jQuery plugin: "X-editable In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery" http://vitalets.github.com/x-editable/
I found many answers to be out of date on this topic, but adamb's was the easiest solution for me, thank you.
However, his solution was bugged to fire multiple times due to not removing the keypress event along with the element.
Here's the updated plugin using $.on() instead of $.bind() and with the keypress event handler being removed when the element is created again.
$.fn.extend({
editable: function() {
var that = this,
$edittextbox = $('<input type="text"></input>').css('min-width', that.width()),
submitChanges = function() {
that.html($edittextbox.val());
that.show();
that.trigger('editsubmit', [that.html()]);
$(document).off('click', submitChanges);
$edittextbox.detach();
},
tempVal;
$edittextbox.click(function(event) {
event.stopPropagation();
});
that.dblclick(function(e) {
tempVal = that.html();
$edittextbox.val(tempVal).insertBefore(that).off("keypress").on('keypress', function(e) {
if ($(this).val() !== '') {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}
});
that.hide();
$(document).one("click", submitChanges);
});
return that;
}
});
http://jsfiddle.net/Hbww2/142/