0

I have an image which is embedded in a div. On the top of the image, I have a fontawsome Icon. When I click on the icon, a list of options opens. These options are basically simple words in divs. I want to print "Hi" when I click on any of these words. I am doing this right now:

$(".label").bind("click", function(e) {
  e.stopPropagation();
  console.log('Hi');

});

The event does not get triggered right now.

I looked at the question posted by someone else jQuery click on div that is on top of another div, I tried to use e.stopPropagation(), but this also does not work.

Here is my code https://jsfiddle.net/06mqh3gs/5/

Any idea?

Bahador Saket
  • 995
  • 1
  • 12
  • 24

3 Answers3

1

since you are creating your Dom elements from the JS side. All you need to do is just add the event listener inside the loop. xD...

 function loadKeywords(){
          for(i=0;i<keyword.length;i++){
            $('<div/>', {
                class:"label",
                id:"label_"+i,
                height: "15",
                html:keyword[i]
            }).appendTo(".form");
               $("#label_"+i).bind("click", function(e) {
              e.stopPropagation();
              alert(i);

            });
          }
       }
Jose CC
  • 865
  • 11
  • 24
  • 1
    Really? You are going to bind an event for each label element inside the loop instead of using jQuery functionality to do the same thing with less code? – JSEvgeny Jan 17 '18 at 18:52
  • @JavaEvgen the question does not ask what is the best approach of implementation. – Jose CC Jan 17 '18 at 19:10
1

I modified your fiddle so it's now working.

Here is your fixed event binder:

$(".profile-img-container").on('click', '.label', function() {
   alert("lalala");
});

You must use this construction to bind an event listener to dynamicly added element and the static container that is always present on page must be provided

JSEvgeny
  • 2,550
  • 1
  • 24
  • 38
1

This answer is very helpful.

To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.

Instead of:

$(".label").bind("click", function(e) {
  e.stopPropagation();
  console.log('Hi');
});

try:

$(document).on("click", ".label", function(e) {
  console.log('Hi');
});
Anthony
  • 1,439
  • 1
  • 19
  • 36
  • That answer you have mentioned does really clear up things related to the question. But the accepted answer is just a trash in my opinion... – JSEvgeny Jan 17 '18 at 19:57
  • Not trash if the OP wants different click functions for each `.label` but definitely way less efficient if the OP wants the same click function for each `.label`. – Anthony Jan 17 '18 at 20:03
  • 1
    Well you are right, but it says "I want to print "Hi" when I click on any of these words." – JSEvgeny Jan 17 '18 at 20:11