This is because the universal dial "*"
(see documentation) enables the click on elements even not yet loaded in the DOM, because it selects precisely "any element", regardless of whether it was loaded or not in the DOM, because it is not specific, it means anyone.
When using a specific selector, such as $("body").click(...
, it is necessary that the element exists 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 an event click
pointing to the 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 will show result:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Clique aqui.</div>
<script>
$( "div" ).click(function( event ) {
console.log( "clicked: " + event.target.nodeName );
});
</script>
In this third example, I will use the universal selector before the div
and will show that the div
was 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 not yet existing in the DOM is using the method .on()
. See that the script is positioned before the 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>
Same thing, only works in pure php
– Alê Moraes
Try using Document instead of body:
$(document)
– Francisco
I discovered the error, js was loading before in head, now I do not know why js only worked with the '*'
– Alê Moraes