Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing event data in the inline event handlers

Tags:

I have an <input> which has an onkeydown inline event handler. In this handler, I'd like to call a function and pass a special parameter to it - the event data.

When I want to handle events (e.g. onmousemove) for the whole document, I use the following code:

document.onmousemove=function(e) { // here I can make a good use of the 'e' variable, // for example extract the mouse coordinates from it } 

And it works (although I don't know where the e variable - event data - comes from).
But this time I want to use the function only for the <input> mentioned above.
I need to pass the event data to the function so it can get the pressed key's code. And I want to do it in that inline event handler. I've created a function:

function myfunc (e) {     var evt=window.event?event:e;     var code=evt.keyCode;     alert (code); } 

and tried all of these methods:

<input onkeydown="myfunc(this)">

<input onkeydown="myfunc(this.onkeydown)">

<input onkeydown="myfunc(onkeydown)">

But none of them worked, the alert window kept displaying "undefined".
I looked for a solution to my problem in Google, but didn't find anything that could help me solve it.

like image 713
rhino Avatar asked Oct 02 '10 16:10

rhino


People also ask

What is inline event handler?

An event handler is a JavaScript function that runs when an event fires. An event listener attaches responsiveness to a given element, which allows the element to wait or “listen” for the given event to fire. Events can be assigned to elements via inline event handlers, event handler properties & event listeners.

How do you pass an event to a function in HTML?

To pass an event object to a function in JavaScript, we can use the addEventListener method. const onClick = (ev) => { ev. preventDefault(); console.

How do event handlers pass arguments?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

What are events and event handlers?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.


1 Answers

<input onkeydown="myfunc(event)">

function myfunc (e) {     e = e || window.event;     var code = e.keyCode;     alert (code); } 
like image 167
25 revs, 4 users 83% Avatar answered Nov 26 '22 19:11

25 revs, 4 users 83%