Javascript How to force to click key? - javascript

force someone to click a key with javascript code.
For example:
$("#gameCanvas").mousedown(function(ev){
if(ev.which == 3)
{
this blank is for that want.
} });
I want to force users to click space button when they clicked right mouse as you see.

You could try a solution like the following one. This the link to the jQuery api doc.
$("#gameCanvas").mousedown(function(ev){
if(ev.which == 3)
{
// Create a new jQuery.Event object with specified event properties.
var e = jQuery.Event( "keydown", { keyCode: 32 } );
// trigger an artificial keydown event with keyCode 32
jQuery( "body" ).trigger( e );
} });

Related

How can I check for two different events simultaneously [duplicate]

Okay so I can detect a mouseover using .on('mouseover')
and I can detect keypresses using
$(document).keypress(function(e) {
console.log(e.which);
}
but how do I detect which image my mouse is hovering over when I press a certain button?
the idea is to be able to delete an image by pressing d while hovering over it. any ideas ?
You can just toggle a class or data-attribute that shows you which one is currently being hovered
$('img').hover(function(){
$(this).toggleClass('active'); // if hovered then it has class active
});
$(document).keypress(function(e) {
if(e.which == 100){
$('.active').remove(); // if d is pressed then remove active image
}
});
FIDDLE
I'v added a better example with jsFiddle:
http://jsfiddle.net/cUCGX/ (Hover over one of the boxes and press enter.)
Give each image an on('mouseover') and set a variable based on that image.
So
var activeImage = null;
myImage.on('mouseover', function() {
activeImage = 'myImage';
});
myImage2.on('mouseover', function() {
activeImage = 'myImage2';
});
$(document).keypress(function(e) {
if (e.which == 'certainKeyPress' && activeImage) {
//do something with activeImage
console.log('The cursor was over image: ' + activeImage + ' when the key was pressed');
}
});
Maybe also add an onmouseout to each image as well to clear activeImage if you want the key press to only work WHEN being hovered.
You should use a mousemove event to permanently store the x & y position in a global variable.
Then, in the keypress handler, grab the element at the last-known mouse position with the document.elementFromPoint(x, y) method.
See https://developer.mozilla.org/en-US/docs/Web/API/document.elementFromPoint
I'm going to go ahead and necro this as I was playing around with this and found I liked my quick solution more. It may not be the best, but it worked better for my needs where I needed a namespace type solution in that the handler would be removed when the dom was in a certain state (sortable):
// Create handler for binding keyup/down based on keyCode
// (ctrl in this example) with namespace to change the cursor
var setCursorBindings = function() {
$(document).on('keydown.sortable', function(event) {
if (event.keyCode === 17) {
$('body').css('cursor', 'pointer');
}
}).on('keyup.sortable', function(event) {
if (event.keyCode === 17) {
$('body').css('cursor', 'inherit');
}
});
};
// Create a handler for reverting the cursor
// and remove the keydown and keyup bindings.
var clearCursorBindings = function() {
$('body').css('cursor', 'inherit');
$(document).off('keydown.sortable').off('keyup.sortable');
};
// Use the jQuery hover in/out to set and clear the cursor handlers
$('.myElementSelector').hover(function() {
setCursorBindings();
}, function() {
clearCursorBindings();
});
Tested in Chrome v41
Use this to test whether the mouse is over the image with id img:
$('#img').is(":hover")

jquery - add event handler on event that takes another event as argument

I am trying to call a function scheduleAdd when the enter button is hit, but I only want it to work if an input with the id 'addSchedule' is in focus. Here's what I have:
$('#addSchedule').focus(function(e) {
var evt = e || window.event;
if(evt.keyCode == 13) {scheduleAdd};
});
I know the code inside the .focus works, because I tried it on its own and it triggers the function scheduleAdd when the enter key is hit. How can I make this conditional on 'addSchedule' being in focus?
Also, more generally, I was wondering if there's a standard way to ascribe event handlers conditional on a second event, such as nesting .on() or something.
Thanks.
Demo on fiddle
HTML:
<form>
<input id="addSchedule" type="text" />
</form>
Javascript:
$('#addSchedule').keydown(function (event) {
if (event.which == 13) {
event.preventDefault(); // This will prevent the page refresh.
scheduleAdd();
}
function scheduleAdd() {
alert("Add the schedule");
}
});
Simply the keydown event, and decide to do something or nothing based on whether the current element has the specified id:
$(document).on("keydown", function() {
if (!$("#addSchedule").is(":focus")) return;
// do stuff
});
Alternatively you can also check for the identity of the focused element with document.activeElement.id === "addSchedule" if you don't mind that's not enough jQuery. ;-)

jQuery: trigger keypress function on entire document but not inside inputs and textareas?

I have this …
$(document).keypress(function(e) {
if ( e.keyCode === 119 ) // w
doSomething();
});
Wo when pressing "w" on my document the doSomething() function fires. How can I prevent it from firing when I'm currently typing (in focus) in an input field or textarea?
You'll have to filter out the elements after the event and not in the selector, like this
$(document).on('keypress', function(e) {
var tag = e.target.tagName.toLowerCase();
if ( e.which === 119 && tag != 'input' && tag != 'textarea')
doSomething();
});
this checks the tagname of the event.target, the element the event originated from, and only fires the function if the event did not originate from an input or textarea.
If your event handler is bound to document, the event will have already been raised on the input element and bubbled up to the html element, so you will have to handle the exclusion within the code for the handler itself. The alternative is specifically binding a second handler for the input elements which prevents the event from bubbling, but that is probably not the right approach.
Code demo
$(function() {
$(document).keypress(function(e) {
if ($(e.target).is('input, textarea')) {
return;
}
if (e.which === 119) doSomething();
});
});​
p.s. you can have a look at the jQuery event object documentation to see what properties it exposes.
In jQuery, e.which is the normalized property, not e.keyCode.
To check if you are not in an input you can check the document.activeElement:
$(document).keypress(function(e) {
if (e.which === 119 && !$(document.activeElement).is(":input,[contenteditable]")) {
doSomething();
}
});
Demo. http://jsfiddle.net/pxCS2/1/
The easiest and perfect solution is:
$(document).keypress(function(e) {
if (e.which == 119 && !$(':focus').length) {
doSomething();
}
});

jQuery.fn.autoResize and Return Key

I am using the following library:
https://github.com/padolsey/jQuery.fn.autoResize
for changing the dimension of textarea box.
$('textarea').autoResize();
By default the Return key in the textarea generate a new line.
How can I disable the autoResize on the Return key action?
Actually I use the Return key to trigger another action:
$("textarea").keypress(function(event) {
if ( event.which == 13 ) {
alert("Handler for .keypress('enter') called.");
}
});
but at the same time I would like to disable the autoResize just on enter keypress.
I did try the following code, but it does not work:
$("textarea").keypress(function(event) {
if ( event.which == 13 ) {
alert("Handler for .keypress('enter') called.");
event.stopPropagation();
}
});
$('textarea').autoResize({
onBeforeResize: function(event){
console.log('Before');
event.stopPropagation();
}
});
You may also want to try event.stopImmediatePropagation() if the handler for autoResize is attached directly to the textarea.
And given stopImmediatePropagation, you will need to make sure your event handler is registered before the autoResize.

jQuery event binding with accessibility in mind - click and keypress

Just a quick question, I seem to do this a lot:
$saveBtn.bind("click keypress", function(e)
{
if (e.type != "keypress" || e.keyCode == 13)
{
// Do something...
return false;
}
});
Is there a quicker way to bind an 'action' listener to a button? I want to always ensure my buttons with event listeners fire on both clicks and the enter key...this seems like it'd be a fairly common thing to want to do but found nothing on google. Any thoughts?
Thanks.
The click event doesn't actually handle the keypress in every case, it's the button that is making the click event work. When you use a div with a tabindex attribute to make it keyboard accessible, the click handler will not trigger when you press enter.
HTML
<div id="click-only" tabindex="0">Submit click only</div>
<div id="click-and-press" tabindex="0">Submit click and press</div>​
jQuery
$("#click-only").click(function (e) {
addToBody(); // Only works on click
});
$("#click-and-press").bind("click keypress", handleClickAndPress(function (e) {
addToBody(); // Works on click and keypress
}));
function addToBody() {
$("body").append($("<p/>").text("Submitted"));
}
function handleClickAndPress(myfunc) {
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
So to answer the question, I don't think there is a better way (that works in every case) other than yoda2k's solution.
By binding it with click will do the job, no need for keep press. Example
You could create a second function which handles the additional logic and pass your function as a parameter:
function handleClickAndPress(myfunc)
{
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
$saveBtn.bind("click keypress", handleClickAndPress(function (e) {
// do your stuff here
}));
If it's part of a form you could just listen for the "submit" event?

Categories

Resources