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
Related
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!
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();
}
});
});
I've gotten hundreds of aids from this site. thanks. This is my first question.
Which object is a modal window (alert popup) into the Dom. How can i refer it? How can i know if open or closed? Something like this: if (alertPopup is open) {..code...}
My code is this (i use jQuery):
<script type="text/javascript">
$(document).ready(function(){
var myButton = $('#mybutton')
myButton.click(function(){
if ($('#myinput').val() == '') {
alert('input Empty!');
} else {
// More code.
}
});
$(document).keyup(function(e){
if (e.keyCode == 13) myButton.trigger('click');
})
});
</script>
<body>
<input id="myinput" />
<button id="mybutton">Show alert</button>
</body>
The purpose of the code is trigger up the event 'click' on the button whith key 'enter'. It works, but when i close the popup, again with key 'enter', the popup comes again an again. I need to disable event 'click' of my button or unbind the trigger action when the popup is displayed.
I would't like to make my own modal windows.
thanks in advance.
You can move the handler to its own function and programmatically bind/unbind it to the event:
$(document).ready(function(){
var myButton = $('#mybutton')
console.log('whee');
myButton.click(clickHandler);
$(document).keyup(function(e){
if (e.keyCode == 13) myButton.trigger('click');
})
});
function clickHandler(){
$('#mybutton').unbind('click', clickHandler)
if ($('#myinput').val() == '') {
alert('input Empty!');
} else {
// More code.
}
}
However, it looks more like you're trying to deal with enter buttons in a form submission style. I'd recommend wrapping this whole thing in a form and dealing with it as such.
See http://jsfiddle.net/ruBY4/ for a cleaner form-based solution.
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/
I have the following function to open an overlay menu:
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
});
To hide the menu, I would like the user to be able to click on any area outside ".context-switch-menu"
I am trying with :not() but with no success..
$('body').click(function(e) {
if ($(e.target).hasClass('context-switch')) {
return;
}
$(".context-switch-menu").hide();
});
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
return false;
});
The reason this can be difficult is because of event bubbling.
You can try something like this:
$('.context-switch').click(function(e) {
e.stopPropagation();
$(".context-switch-menu").toggle();
});
$(".context-switch-menu").click(function(e){
e.stopPropagation();
});
$("body").click(function(e){
$(".context-switch-menu").hide();
});
The e.stopPropagation() prevents the click event from bubbling to the body handlers. Without it, any click to .context-switch or .context-switch-menu would also trigger the body event handler, which you don't want, as it would nullify the effect of the .context-switch click half the time. (ie, if the state is hidden, and then you click to show, the event would bubble and trigger the body handler that would then hide the .context-switch-menu again.)
Without testing, would something like this work?:
$('.context-switch').click(function() {
$(".context-switch-menu").show();
});
$(document).click(function() {
$(".context-switch-menu").hide();
});
Instead of using document, 'html' or 'body' may work as well.
$(document).on('click', function(e) {
if (e.target.className !='context-switch-menu') {
$(".context-switch-menu").hide();
}
});
Just an idea here, based on what what others have suggested in the past:
$(document).click(function(e){
//this should give you the clicked element's id attribute
var elem = $(e.target).attr('classname');
if(elem !== 'context-switch-menu'){
$('.context-switch-menu').slideUp('slow');
//or however you want to hide it
}
});
try this, we don't want to call a function when you clicked on the element itself, and not when we click inside the element. That's why we need 2 checks.
You want to use e.target which is the element you clicked.
$("html").click(function(e){
if( !$(e.target).is(".context-switch-menu") &&
$(e.target).closest(".context-switch-menu").length == 0
)
{
alert("CLICKED OUTSIDE");
}
});
Live fiddle: http://jsfiddle.net/Xc25K/1/