0

I tried method : Attaching click event to a JQuery object not yet added to the DOM

but seems not working in my situation. After I created dom elements by jquery, the newly created elements are not accessible. What I want is to after clicking "click me" button, and the image will show up and I hope click the image and a div (#color-picker-box) to show up.

My code: https://codepen.io/MoMoWongHK/pen/ZXbWYb

Mikhail
  • 11,067
  • 7
  • 28
  • 53

3 Answers3

1

add the number sign # when calling the id of your div,

from

$("myDiv").on("click" ,".color-picker-icon" , function(){
    alert("hi");
    $("#color-picker-box").removeClass("display-none");
});

to

$("#myDiv").on("click" ,".color-picker-icon" , function(){
    alert("hi");
    $("#color-picker-box").removeClass("display-none");
});
Nove Sanchez
  • 109
  • 5
1

You just missed # while using myDiv as a selector!

Wrong:

$("myDiv").cl....

Corrected:

$("#myDiv").cl.....
Abhishek Kumawat
  • 780
  • 1
  • 10
  • 25
0

You need to use event Delegation since the element is not added to dom yet. You need to capture the click on its parent.

$('#myDiv').on("click", "#color-picker-box", function(e){
  console.log('color box clicked');
});

Read more about it on: https://learn.jquery.com/events/event-delegation/
http://api.jquery.com/on/

anshu purohit
  • 176
  • 2
  • 10