简体   繁体   中英

Get onmouseover 'event' object when setting function from inside javascript

I used to have an inline onmouseover() defined and used the event object:

<script>
function foo(e, bar) {
  var x = e.clientX;
  var y = e.clientY;
  // do something with the coordinates and bar
}
</script>
<div onmouseover="foo(event, 'barValue')"></div>

Now I'm generating the <div> html via java script, I can't figure out where to get my event object from.

var d = document.createElement("div");
d.onmouseover = function() { foo(event, dynamicBarValue); };

I am not looking for a solution using JQuery.

You are going to receive the evt as a first parameter of your listener (check EventTarget.dispatchEvent() ). So you could simply do:

var d = document.createElement("div");
d.onmouseover = function(evt) { foo(evt, dynamicBarValue); };

You are using the On-Event handler Properties syntax for adding the event . However, you are trying to overwrite the event (Property) in JS code by using Syntax
d.onmouseover = function() ... .

You have already specified the event in HTML attribute
<div onmouseover="foo(event, 'barValue')"></div> and this code binds the function foo with the mouseover event. When you try to add the d.onmouseover event again in the JS file it will overrwrite the property and create a new handler for your event.

So, You only need to define the attribute in either the HTML code or JS Code.

Moreover, the first argument is the event information.

From MDN ,

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

event - for all event handlers, except onerror.
event, source, lineno, colno, and error for the onerror event handler. Note that the event parameter actually contains the error message as string.

So, you can achieve the desired effect be defining only one event handler.

 function foo(e, bar) { var x = e.clientX; var y = e.clientY; // do something with the coordinates and bar console.log(x,y,bar) } 
 <div onmouseover="foo(event, 'barValue')">Test</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM