The jQuery Event Object
In this page:
Event Type
Every event handler receives an event object, and its type property tells you exactly which kind of event fired, useful when one function is shared across several event types.
Example: Event Type
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click or hover</button>
<script>
$("#btn").on("click mouseenter", function(event) {
console.log("Event type:", event.type);
});
</script>
</body>
</html>
Target Element
event.target is the original element that received the event, which may be a child element nested deep inside whatever you actually attached the handler to.
Example: Target Element
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"><span>Inner text</span></div>
<script>
$("#box").on("click", function(event) {
console.log("Target:", event.target.tagName);
});
</script>
</body>
</html>
Current Target
event.currentTarget is always the element the handler was directly attached to, which can differ from event.target when the event bubbled up from a descendant -- this distinction matters most in delegated events.
Example: Current Target
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"><span>Inner text</span></div>
<script>
$("#box").on("click", function(event) {
console.log("currentTarget:", event.currentTarget.id, "target:", event.target.tagName);
});
</script>
</body>
</html>
Mouse Coordinates
Mouse events carry coordinate properties like clientX and clientY, giving you the pointer's position relative to the browser viewport at the moment the event fired.
Example: Mouse Coordinates
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="pad" style="height:100px">Move mouse here</div>
<script>
$("#pad").on("mousemove", function(event) {
console.log("X:", event.clientX, "Y:", event.clientY);
});
</script>
</body>
</html>
Prevent Default
Calling event.preventDefault() stops the browser's normal built-in action for that event, such as following a link's href or submitting a form, without stopping the event from continuing to propagate.
Example: Prevent Default
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<a id="link" href="https://example.com">Click me</a>
<script>
$("#link").on("click", function(event) {
event.preventDefault();
console.log("Navigation stopped");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: