I have 2 click events. One appends an IMG which includes another click event. It doesn't work obviously. I know that I have to use jQuery's .ON, but I just can't figure out how and where.
My code:
$( document ).ready(function() { // The one below (.choimh) isn't triggered anymore $('.choimg').click(function(){ }); // Switch to chosen color $('.color').click(function(){ $(".thumbs").append('<a href="#"><img id="image'+u+'" class="choimg" src="/img/products/mini/'+colnumber+'-'+ i + '.jpg" />'); }); });
The .color div is on a completely different place than .choimg.
I just can't figure out how to use .ON.
So Why Does It Happen? JQuery OnClick Method is bound to an element or selector on page ready/load. Therefore if that element you want to click isn't there at the time of page ready, the binding can't happen.
. click events only work when element gets rendered and are only attached to elements loaded when the DOM is ready. . on events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
. append() adds the parameter element inside the selector element's tag at the very end whereas the . after() adds the parameter element after the element's tag.
It used to be the live
or delegate
functions that did this kind of thing. Now you can do it like this:
$(document).on('click', '.choimg', function(e) { //do whatever });
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