Pavel Zagalsky
Pavel Zagalsky

Reputation: 1636

Creating a clickable div within a div

for some reason I cannot make this simple thing to work:

     for (var i = 0; i < results.length; i++) { 
      var object = results[i];
      $("#recipes_names").append("<div id ="  + "recipe" + i + " >");
      $("#recipes_names").append(object.get('recipe_title'));
      console.log(object);
      console.log(object.id + ' - ' + object.get('recipe_title'));
      $("#recipe1").click(function(e) {
        e.stopPropagation();
        alert("inside click");
    });
    }
  },

I create divs within the "recpie_names" div with the name "recipe0"/"recipe1" etc and I can't for the life of me make them clickable. I'm sure there's a tiniest of mistakes that I make here but I just can't nail it down. Can you help me out?

Upvotes: 0

Views: 84

Answers (3)

Charkan
Charkan

Reputation: 831

You have to delegates your event

$('#recipes_names').on('click', 'div[id^=recipe]', function(e){
    e.stopPropagation();
    alert("inside click");
});

Upvotes: 1

CodyEngel
CodyEngel

Reputation: 1501

It looks like you are generating these divs after the fact. So .click will not work.

Try:

$("#recipe1").on('click', function(e) {
    e.stopPropagation();
    alert("inside click");
});

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Add a class to the div which is appended and instead of adding event on base of id add just one event on class selector and write just on event:

$("#recipes_names").append("<div class='recipe' id ="  + "recipe" + i + " >");

and:

$(document).on("click",".recipe",function(e) {
        e.stopPropagation();
        alert("inside click");
    });

Upvotes: 1

Related Questions