0

Attempting to remove and reapply function to the onmouseover event of an element. Not sure how to go about this, have attempted several ways without any luck.

<!DOCTYPE html>
<html>
<body>

<button id="my_button" onmouseover="myFunction(this)">Try it</button>

<script>

function myFunction(ele) {
  alert("hi")
  document.getElementById("my_button").onmouseover = "null";
  document.getElementById("my_button").onmouseover = "myFunction(this)";
}

</script>
</body>
</html>

3 Answers3

0

you can use :


<button id="my_button" onmouseover="alert('hi')">Try it</button>
  • Im referring to applying a function I premade in a javascript file. document.getElementById("my_button").onmouseover = "myFunction(this)"; – countdookoo Jul 22 '22 at 01:21
0

The issue is that you're setting the button onmouseover property to a string in myFunction instead of to a function object.

The HTML parser creates an anonynmous handler function from the onmousever attribute value for you, but setting the button property to a string in JavaScript won't create such a function. Try

<!DOCTYPE html>
<html>
<body>

<button id="my_button" onmouseover="myFunction.call(this, event)">Try it</button>

<script>

function myFunction(event) {
  alert("hi, this.tagName = " + this.tagName)
  document.getElementById("my_button").onmouseover = "null";
  document.getElementById("my_button").onmouseover = myFunction; // a function object
}

</script>
</body>
</html>

Notice I've modified myFunction to see the button object as its this value, and its argument to be the mouse event raised for the click, and changed the call in the handler generated by the HTML to call myFunction as if it were the actual event handler. This was to keep the calls to myFunction seeing the button as its this value and event as its argument in both cases.

For more about the handler created by the HTML parser see a previous answer (disclaimer: of mine) to 'this inside event handler from HTML attribute' that goes into greater detail.


Note that for various reasons it is no longer recommended to create event handlers using oneventname attribute values in HTML when you can add them using element.addEventListener in JavaSript as part of initialization.

traktor
  • 17,588
  • 4
  • 32
  • 53
  • Thank you, works perfect! Just started Javascript, have been calling functions like this in html, onmouseover= "myFunction(this)"; I assumed this was the only way to pass it, appreciate the detail. – countdookoo Jul 22 '22 at 01:57
0

try

<!DOCTYPE html>
<html>
<body>
<button id="my_button" class="mousemove" >try it</button>
<script>
document.getElementsByClassName("mousemove")[0].onmousemove = function(){
  alert("hi")
  document.getElementById("my_button").onmousemove = function(){ return null }
}
</script>
</body>
</html>