Attempting to remove and reapply function to the onm ouseover 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" onm ouseover="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>
CodePudding user response:
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" onm ouseover="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.
CodePudding user response:
you can use :
<button id="my_button" onm ouseover="alert('hi')">Try it</button>
CodePudding user response:
try
<!DOCTYPE html>
<html>
<body>
<button id="my_button" >try it</button>
<script>
document.getElementsByClassName("mousemove")[0].onmousemove = function(){
alert("hi")
document.getElementById("my_button").onmousemove = function(){ return null }
}
</script>
</body>
</html>