By using target property, You can know the element on which you clicked. First, select the document and define click event on it in jquery. Now, define an anonymous function in the click event argument that will receive the event details like the original event (ex-mouse event), event type (ex- click), event target (ex- element name), etc. To get the name of the element use nodeName or tagName JS properties.
See examples-
<!DOCTYPE html>
<html>
<head>
<title>Jquery target</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 id="position" align="center">Click on any element to print it</h1>
<div style="width:300px;height:300px;border:1px solid black;">
this is div
</div>
<button style="margin:20px;">This is button</button>
<script>
$(document).ready(function(){
$(document).click(function(e){
alert(e.target);
});
})
</script>
</body>
</html>
Print clicked-element name from document
<!DOCTYPE html>
<html>
<head>
<title>Jquery target</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 id="position" align="center">Click on any element to print it</h1>
<div style="width:300px;height:300px;border:1px solid black;">
this is div
</div>
<button style="margin:20px;">This is button</button>
<script>
$(document).ready(function(){
$(document).click(function(e){
alert(e.target.nodeName);
});
})
</script>
</body>
</html>
type property: Know the event name
For example- click event
<script>
$(document).ready(function(){
$(document).click(function(e){
alert(e.type);
});
})
</script>
originalEvent property
<script>
$(document).ready(function(){
$(document).click(function(e){
alert(e.originalEvent);
});
})
</script>
Publish A Comment