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.
It used to be the
live
ordelegate
functions that did this kind of thing. Now you can do it like this:You should use something like:
General prototype is
on(eventType, selector, function)
, you can use other events too.For more info see this.
jQuery's on does a lot, but for your specific case, you want to put "on" onto a DOM object that is not loaded up after the DOM has loaded. This allows the event to bubble up to this DOM object which, then, in turn, delegates the event to the appropriate DOM item based on the second selector your provide.
If you follow the link above, there is a ton of information about it in the jQuery documentation. Specifically, this is important for your case...
In any case, you need to bind to the thing that already exists, and provide a second selector for the thing that is going to be added that you want to have the actual event, along with the event, and the functionality. Something like this...
Note that it is important that the "thing that exists" is as low as you can possibly get it in the DOM for efficiency. For example, it is not preferable to put the selector on the 'body' or at the document level. Keep this in mind.
Hopefully this gives a bit of a better understanding for what you want to do. I highly encourage you to read the jQuery documentation as it is very good.