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

4
  • 3
    Please post your code here, users shouldn't have to go to a different site to see it Commented Sep 16, 2017 at 16:07
  • 1
    It a simple typographical error. $("myDiv") should be $("#myDiv") with a # as you are selecting by ID not by tagname. Commented Sep 16, 2017 at 16:11
  • That is a silly error... Commented Sep 16, 2017 at 16:29
  • 1
    @MoMoWongHK ... that should make you consider removing the post. Commented Sep 16, 2017 at 16:30

3 Answers 3

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");
});
Sign up to request clarification or add additional context in comments.

Comments

1

You just missed # while using myDiv as a selector!

Wrong:

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

Corrected:

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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.