Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Click event doesn't work after append. (Don't know how to use .ON)

Tags:

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.

like image 838
user2669261 Avatar asked Aug 12 '13 20:08

user2669261


People also ask

Why click is not working in jQuery?

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.

What is the difference between .on click function ()) and .click function?

. 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).

How do you trigger a click element?

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.

What is the difference between the append () and after () methods in jQuery?

. 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.


1 Answers

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  }); 
like image 55
Phillip Schmidt Avatar answered Sep 22 '22 08:09

Phillip Schmidt