2

My point is to trigger the onmouseover event in javascript code. I used the function onmouseover() on an element. But it doesn't works in some situations.

This is a demo code:

HTML file:

<p id="p-id">Text Text</p>

External Javascript file:

var myP = document.getElementById("p-id");
myP.addEventListener("mouseover", function() {
    this.style.backgroundColor = "red";     
});
// trigger the mouseover:
myP.onmouseover(); // console error: onmouseover is not a function.

But onmouseover() function works well when I use the attribute onmouseover="javascript code" on the element:

HTML file:

<p id="p-id" onmouseover="this.style.backgroundColor='red'">Text Text</p>

External Javascript file:

var myP = document.getElementById("p-id");
// trigger the mouseover:
myP.onmouseover(); // works well 

I have been searching the reason for ages but I have no clues.

Lansh
  • 23
  • 3

1 Answers1

3

The onmouseover property is a setter/getter on HTMLElement.prototype:

var myP = document.getElementById("p-id");
const descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onmouseover');
console.log(descriptor);
console.log(descriptor.get.call(myP));
<p id="p-id" onmouseover="console.log('fn')">Text Text</p>

When the getter is invoked, it will return either the handler that was previously attached using the setter, eg elm.onmouseover = someFn, or it will return the inline handler function.

In your upper code, the handler is neither inline nor is it attached via invoking the setter, so accessing the onmouseover property of the element returns null, which can't be called.

In your lower code, the handler is inline, so it's returned by accessing the onmouseover property, which invokes the getter.


It's good practice to never use inline handlers they have too many problems to be worth using, and to also not attach handlers via .on properties (because then, if another script tries to attach a handler to the same element, it'll overwrite the earlier handler).

If you want to trigger a listener function you just attached, you can either save the function in a variable first, then call it:

var myP = document.getElementById("p-id");
const fn = () => myP.style.backgroundColor = "red";     
myP.addEventListener("mouseover", fn);
fn();
<p id="p-id">Text Text</p>

Or dispatch an event to the element through the DOM:

var myP = document.getElementById("p-id");
myP.addEventListener("mouseover", () => myP.style.backgroundColor = "red");
myP.dispatchEvent(new Event('mouseover'));
<p id="p-id">Text Text</p>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320