Event handling in javascript html

Hello,

I have followed w3schools to create an element such that when I hover the mouse over this element, it starts giving me the coordinates of the mouse pointer. When the mouse is moved out of this element, the coordinate information is no longer displayed.
The code that I have written is s follows

<html>
	<head>
		<script>
			function myFunction(e) {
				var x=e.clientX;
				var y=e.clientY;
				var coor="Coordinates: ("+x+" , "+y+")";
				document.getElementById("demo").innerHTML=coor;
			}
			function clearCoor() {
				document.getElementById("demo").innerHTML="";
			}
		</script>
		<style type="text/css">
			div {
				width:100px;
				height:100px;
				border:1px solid black;
			}
		</style>
	</head>
	<body>
		<div onmousemove="myFunction(event)" onmouseout="clearCoor()"></div>
		<p id="demo"></p>
	</body>
</html>

In the above code, I am not able to understand the event parameter in the following line

		<div onmousemove="myFunction(event)" onmouseout="clearCoor()"></div>

Is this an inbuilt keyword etc. In what context do we use and in what we don’t?

kind of.

you never use it. resp. you never use HTML event attributes. You use event listeners defined purely in JavaScript and then you don’t need to pass the event parameter yourself.

1 Like

I agree with Dormlich. Your code can be more simplest and pure with js code like this:

<html>
	<head>
		<script>
			var divElm=document.getElementById('divCoor');
            var parElm=document.getElementById("demo");
            divElm.onmousemove =function(e){  
                var x=e.clientX;
                var y=e.clientY;
                var coor="Coordinates: ("+x+" , "+y+")";
                parElm.innerHTML=coor;
};
		</script>
		<style type="text/css">
			div {
				width:100px;
				height:100px;
				border:1px solid black;
			}
		</style>
	</head>
	<body>
		<div id="divCoor"></div>
        <p id="demo"></p>
	</body>
</html>

Specially about the event that you asked…event (or e sometimes that you’ll see) is an argumment that we passed to function corresponding to MuseEvent object. See the follow documentation https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.