I was using the $.click()
method for triggering some events. But then I needed to set some events for some HTML elements before the elements were declared. Let's take this as an example:
<script>
$('div.hide').click(function() {
$('div.hide').css({'display' : 'none'});
});
</script>
<div class="hide">some text</div>
The downside is that when setting the .click()
method, the div.hide
elements doesn't exist, so no trigger is set.
So I turned to the .on()
method, like so:
<script>
$('div.hide').on('click', function() {
$('div.hide').css({'display' : 'none'});
});
</script>
<div class="hide">some text</div>
But this also doesn't work. I thought calling .on()
would make all existent and future div.hide
elements trigger the 'click' function()
.
I managed to get past this inconvenience, but for my own knowledge I'd like to know what was I doing wrong. Is there no way to assign a trigger to future HTML elements?
My solituion was:
<script>
$(document).ready( function() {
$('div.hide').click(function() {
$('div.hide').css({'display' : 'none'});
});
});
</script>
<div class="hide">some text</div>
You missed the three-argument version:
$('body').on('click', 'div.hide', function() { ... });
That puts the handler on the <body>
but it catches the events that bubble and invokes the handler when the target element matches the selector (the second argument).
The handler doesn't have to go on the <body>
; it can be any parent container element of your <div>
.
The "on" method replaces the older "live" and "delegate" methods, as well as "bind" itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With