JavaScript - onClick method

To detect a click on an element inside a web page, simply use the JavaScript method onClick() which takes a simple event handler as a parameter and then retrieves the type of the element pressed.

To do this, it is necessary to render our code so that it listens for the event that is going to be triggered. You have to use the method onClick. You can extract the pressed element from the event.

< form> 
Enter a name< br />
< input id="text" />
< input type="button" value="Validate" />

< h3 id="res">
< script>
document.onclick= function(event) {
// the event is used to detect which component the click went to
if (event===undefined) event= window.event;
var target= 'target' in event? event.target: event.srcElement;

document.getElementById("res").innerHTML = "I clicked on an element of type "+target.tagName;
};

Execution:
Enter name


A click outside of the web page such as the back button and in some browsers cannot be detected for security reasons.