I need to trigger click on some keypress action, also if it's a up or down key on my keybord script will be removing some class from specify element. So keypress is working but trigger and up down press not, this is my code, ths for help.
$('.main_search_field').keypress(function(evt){
$('.live_search_plugin').addClass('visible');
var scroll_pane = $('.scroll-pane');
scroll_pane.click();
scroll_pane.trigger('click');
if (evt.keyCode == 40) {
$('.live_search_list ul li').removeClass('active');
}
});
You can try following code:
var e = jQuery.Event("keypress");
e.which = 50;
$(".main_search_field").trigger(e);
In e.which put code for required character.
You have to check for the evt keypress like so:
if (evt.which == 40) { }
When using keypress, usually I check for which key I want to interact with before running any code inside my function. If you don't do this, your code will run with any keypress.
.keypress() might not be your best solution here, you could be better off using keydown() and keyup(), or to use the full version: .bind('keydown', handler) (ditto for keyup)
From the jquery docs:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
http://api.jquery.com/keypress/
.click() is shorthand for .trigger("click") and you are using it fine, but do you actually have a click handler on $('.scroll-pane)?
Your code will (assuming browser dependencies) cause two clicks to be triggerred on $('.scroll-pane') and then the if() to be evaluated. But you haven't shown us your click handler for scroll-pane so we can't see if that's at fault.
Related
I am looking for a way to simulate a keyboard press (like the titled suggests). I have looked around and I have found mainly these 2 SO questions:
Is it possible to simulate key press events programmatically?
Simulate keypress without jquery
The issue with those are that they both use the KeyboardEvent.initKeyboardEvent() event which according to MDN it is deprecated. Is there a different way of accomplishing the same thing without that deprecated function?
I would like to know this because I am creating a script for YouTube using Chrome's TamperMonkey extension. This script will, when [space] is pressed, trigger K. K is YouTube's toggle play/pause button. I have the [space] listener working perfectly with the code below:
document.addEventListener("keydown", function(e) {
if(e.keyCode==32) {
e.preventDefault();
}
}, false);
Also I am really looking for a pure JavaScript approach.
If you do this with jQuery you build your event.
https://stackoverflow.com/a/3368599/3257830
If you want to create an event, you initialize the object then dispatch the event.
https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
document.addEventListener("keypress", function(e) {
alert(e.which);
});
var e = new Event("keypress");
e.which = 65;
e.keyCode = 65;
document.dispatchEvent(e);
<p id="r">Alerts on event</p>
I am in the process of upgrading our application's jQuery version from 1.4.2.
I have a chunk of JS, which I don't see why it would work but in fact works in 1.4.2 and not in 1.4.3+
$(document).bind('keydown', 'f3',
function (event) {
alert("f3");
//Do something
});
in jQuery 1.4.2 this WORKS and triggers the event handler only for F3.
When I upgrade to 1.4.3+ the event handler is triggered for any keydown (which I think makes sense).
Does the keydown event know to use the event data and check if the key was pressed?
Can anyone help me clarify if it does or does not, and if not why would this code be working in jQuery 1.4.2?
I checked the release notes and the only thing that changed is added method signatures for the bind and keydown events.
Yes. The event object has all information regarding event. But you need to check for F3 manually using properties such as keyCode and which and such properties.
For example the keyCode for F3 is 114. So you would check it like this:
if(e.keyCode === 114){
//F3 is pressed
}
It might be working for you still because now, the second(optional) argument is eventData to which you're passing 'f3'
Yes you can check for the key property and you should be doing it as follows:
$(document).keydown(function( event ) {
if ( event.which == 114 ) { // 114 is the identifier for F3
//Do some stuff
event.preventDefault();
}
});
I am having plenty of key events here on my page.Is there any way to disable all the keyup/keydown/keypressed events present on page rather than disabling each event separately.
i am looking for solution using javascript/jquery.
Thanks!!
You could do it this way, though I expect it might be horrendously slow on larger pages:
$('*').off('keyup keydown keypress');
That's going to select every single element on the page, then remove any keyup, keydown, and keypress events that are bound to them.
If you want to prevent the user from using the backspace key to navigate to the previous page, you could try the following code:
var inputTags = ['INPUT', 'TEXTAREA'];
$(document).on('keypress', function(e) {
if(e.which === 8 && $.inArray(e.target.tagName, inputTags) === -1)
e.preventDefault();
});
That should restrict the use of the backspace key, except in instances where the focus is an input element where you can enter text (so an <input type="text"> or a <textarea>).
Take a look at this working demo.
Try
$(document).find('*').off('keyup keydown keypressed');
and you should put this into the $(document).ready() block, after all the loaded JS on page (before </body> tag, for example).
you can use preventDefault() function to solve it
$('*').unbind('keyup keydown keypress')
For me worked this combination:
Turn on keypress event
$(document).keypress(function(){
// Code
});
and for turning off this event I have used:
$(document).off('keypress');
$(elem).off('keypress.jstree')
I recently struggled with this as well since I was adding editing features to tree nodes. By looking at the source, I noticed there's an event keypress.jstree being bound with a timeout of 500ms.
Simply adding the above off binding after initializing the tree solved all my issues at once! This works both for static tree structures as well as tree's loaded with ajax data. The version I'm currently using is 3.3.5
Hope this helps.
This code deletes the last key pressed in TextBox2, by using substr.
`$("#TextBox2").val($("#TextBox2").val().substr(0, ($("#TextBox2").val().length-1)));`
//removes last letter pressed.
Is there some way to find out what caused the onChange event on select box in Internet Explorer (>= IE8) - keyboard or mouse?
I have a code which doing something when user selecting a value, and this code works great in Firefox and Chrome but not in IE (no surprise, huh). In IE it works fine only if user uses mouse but not a keyboard, because then it fires a onchange event on every keypress (not on Enter as normal browsers).
So, to fix this behavior I need to know if event is fired using a keyboard and then I will filter it.
Update:
Ok, after playing a bit I found a good solution. Posting it here in case someone will find it useful. Solution below using jQuery but it can be done in pure Javascript too.
This is a code which caused a problem:
$("#mySelectBox").change(function () {
// Do something
});
And this is my solution. It's probably not perfect, but it works in my case. And event handlers could be chained in jQuery, of course. The code below stores initial value of the select and uses it to avoid doing something on initial mouse click - when user expands a select box. Also it filters all keypresses except Enter.
function doSomething(el) {
if (el.data["valueOnFocused"] !== el.val()) {
// Do something
}
}
$("#mySelectBox").focusin(function () {
$(this).data["valueOnFocused"] = $(this).val();
});
$("#mySelectBox").keyup(function (e) {
if (e.which === 13)
{
doSomething($(this));
}
});
$("#mySelectBox").click(function () {
doSomething($(this));
});
Basically the onchange event is supposed to be fired when the user makes a selection then leaves the input (be it select, textbox, radio button, whatever). Since this isn't working in IE, you could try using onblur instead, to detect when the user actually leaves the box. At that point you could read which item is selected and act accordingly. This is more of a workaround, but might do what you need.
Edit: another option would be to detect the pressing of the Enter key, like so:
if(e && e.which){ // NN4 specific code
e = e
characterCode = e.which
}
else {
e = event
characterCode = e.keyCode // IE specific code
}
The characterCode variable now has the "code" of which button was pressed. If it was the enter key, that code will be 13. You could listen for this.
I have a JQuery scroller on a page where each item is a div with an id. each div has a link to the next div in the scroller (all on the same page)
$('a.panel').click(function () {
};
I have a click event to all links with the 'panel' class where I check which links was clicked and then do some ajax processing accordingly:
if($(this).attr('href')=="#item2")
{
//do some processsing
}
and once the processing is done I use the scrollTo JQuery method to scroll to the next div
I need to have it that the user can press the enter key instead of clicking on the link.
Now the problem is:
a. I have several links on the same page that all need to have this behaviour.
b. I need to differentiate which link triggered the click event and do some server-side processing.
Is this possible at all?
I appreciate the quick and helpful responses!!Thanks a million for the help!
Focus + enter will trigger the click event, but only if the anchor has an href attribute (at least in some browsers, like latest Firefox). Works:
$('<a />').attr('href', '#anythingWillDo').on('click', function () {
alert('Has href so can be triggered via keyboard.');
// suppress hash update if desired
return false;
}).text('Works').appendTo('body');
Doesn't work (browser probably thinks there's no action to take):
$('<a />').on('click', function () {
alert('No href so can\'t be triggered via keyboard.');
}).text('Doesn\'t work').appendTo('body');
You can trigger() the click event of whichever element you want when the enter key is pressed. Example:
$(document).keypress(function(e) {
if ((e.keyCode || e.which) == 13) {
// Enter key pressed
$('a').trigger('click');
}
});
$('a').click(function(e) {
e.preventDefault();
// Link clicked
});
Demo: http://jsfiddle.net/eHXwz/1/
You'll just have to figure out which specific element to trigger the click on, but that depends on how/what you are doing. I will say that I don't really recommend this, but I will give you the benefit of the doubt.
A better option, in my opinion, would be to focus() the link that should be clicked instead, and let the user optionally press enter, which will fire the click event anyways.
I would like to focus on the link, but am unfamiliar exactly how to do this, can you explain?
Just use $(element).focus(). But once again, you'll have to be more specific, and have a way to determine which element should receive focus, and when. Of course the user, may take an action that will cause the link to lose focus, like clicking somewhere else. I have no idea what your app does or acts like though, so just do what you think is best, but remember that users already expect a certain kind of behavior from their browsers and will likely not realize they need to press "enter" unless you tell them to.
If you do choose to use the "press enter" method instead of focusing the link, you'll likely want to bind() and unbind() the keypress function too, so it doesn't get called when you don't need it.
http://api.jquery.com/focus/
http://api.jquery.com/bind/
http://api.jquery.com/unbind/
Related:
Submitting a form on 'Enter' with jQuery?
jQuery Event Keypress: Which key was pressed?
Use e.target or this keyword to determine which link triggered the event.
$('a.panel').click(function (e) {
//e.target or this will give you the element which triggered this event.
};
$('a.panel').live('keyup', function (evt) {
var e = evt || event;
var code = e.keyCode || e.which;
if (code === 13) { // 13 is the js key code for Enter
$(e.target).trigger('click');
}
});
This will detect a key up event on any a.panel and if it was the enter key will then trigger the click event for the panel element that was focused.