user13398128
user13398128

Reputation:

Javascript Error with Onload and onmouseout events

I am trying to execute code when the onmuseout/onload events occur, but for some reason my code is not running??

function outFunction() {
  document.getElementById("mouseout").alert("Don't Leave!")
}

function myFunction() {
  document.getElementById("hi").innerHTML = "This DIV is loaded."
}
<div onmouseout="outFunction()" , id="mouseout">DIV</div>
<div id="hi" onload="myFunction()"></div>

Upvotes: 0

Views: 47

Answers (1)

Dai
Dai

Reputation: 155578

outFunction:

The alert function is on window (or the implicit global object). It is not on the returned div element (which is an instance of HTMLDivElement).

Change your function to this:

function outFunction() {
    window.alert("Don't Leave!")
}

Note that this also works (the same alert function is being used, because window is the global object):

function outFunction() {
    alert("Don't Leave!")
}

myFunction:

onload is not defined on HTMLDivElement. You should use document.addEventListener( 'DOMContentLoaded', handler ) instead.

Change your HTML and JavaScript function to this:

<div id="hi"></div>
function myFunction() {
    document.getElementById("hi").innerHTML = "This DIV is loaded."
}
document.addEventListener( 'DOMContentLoaded', myFunction ); // Do NOT put parentheses! i.e. don't put `myFunction()`, just put `myFunction` - because you're passing a function-reference, not a function-call.

Upvotes: 0

Related Questions