Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger a keyup event and pass the key?

Tags:

jquery

bdd

I have a field that "corrects" itself as you type. We have some code written that prevents this functionality when the arrow keys are pressed:

handleKeyUp: function(e) {
    var arrowKeys = _.range(37, 41),
        key = e.which;

    // allow user to move cursor by keyboard
    if ($.inArray(key, arrowKeys) < 0) {
        this.removeInvalidCharacters();
    }
},

We would like to write a unit test for this; however, we can't figure out how to pass e.which via $input.trigger('keyup'). I know the second parameter of trigger allows us to send "extra options"; however, that just passes values more values to the handleKeyUp function. Ideas?

like image 973
Parris Avatar asked May 02 '13 22:05

Parris


People also ask

How do you trigger a Keyup event?

The keyup event occurs when a keyboard key is released. The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs. Tip: Use the event. which property to return which key was pressed.

How do I trigger Keydown event?

HTML and CSS layout: In the given layout, when an input is made in the field, the keyCode value will be logged in the box. The events related to keypresses are as follows : keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed.

When user release key event are triggered?

The jQuery method of keyup() corresponds the keyup event, it is triggered when the user releases an key. It will not fire until the key is released. The difference between this one and the others (keypress and keydown) is that when a key is held down, this event will not fire until the key is released.

Why is Keyup not working?

keyup / keydown seem to only work on elements that are present at document. ready . If you are triggering your event from elements that were altered or injected post pageload, these events will not fire.


1 Answers

Try this -

var e = $.Event("keyup");
e.which = 37; 
$input.trigger(e);

http://api.jquery.com/category/events/event-object/

As of jQuery 1.6, you can also pass an object to jQuery.Event() and its properties will be set on the newly created Event object.

// Create a new jQuery.Event object with specified event properties.
var e = jQuery.Event("keydown", { keyCode: 64 });

// trigger an artificial keydown event with keyCode 64
jQuery("body").trigger( e );
like image 68
Mohammad Adil Avatar answered Oct 28 '22 06:10

Mohammad Adil