This happens because the universal selector "*"
( see documentation ) enables click on elements not yet loaded in the DOM, because it selects just any "element", regardless of whether it was loaded in the DOM, because it is not specific, means anyone .
When using a specific selector such as $("body").click(...
, the element must exist in the DOM, otherwise the event will not take effect because at the time of script execution the element has not yet been rendered and added to the DOM.
In this first example I will create a click
event pointing to div
before it is loaded into the DOM. See that nothing happens:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$("div" ).click(function( event ) {
console.log( "clicked: " + event.target.nodeName );
});
</script>
<div>Clique aqui. Nada irá acontecer!</div>
In this second, I will position the script after the element, and it will show result:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>Cliqueaqui.</div><script>$("div" ).click(function( event ) {
console.log( "clicked: " + event.target.nodeName );
});
</script>
In this third example, I'll use the universal selector before div
and show that div
has been clicked:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$("*" ).click(function( event ) {
console.log( "clicked: " + event.target.nodeName );
});
</script>
<div>Clique aqui</div>
Another example that selects an element that does not yet exist in the DOM is using the .on()
method. Note that the script is positioned before div
:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$(document).on("click", "div", function( event ) {
console.log( "clicked: " + event.target.nodeName );
});
</script>
<div>Clique aqui</div>