Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom class in an array loop wont work

I am trying use a class (question) that will be attached in each element of the array, the loop works fine. My problem is when I try to use the class in jQuery nothing happens, its as if its not there...

I am aware that Angular adds ng-scope and ng-binding classes, could this be preventing jQuery maybe?

When I inspect the DOM theres no errors and my class is there , it just wont work!

Here is my code: HTML

<p ng-repeat="n in ['Human or Lemar King?','Name of your tribe?','Can you Boogie?'] | filter:query" class="question"> {{n}}</p>

jQuery

$(function () {
  $(".question").on('click',function() {
     alert("Ohh hail King Julien!")
  });      
});
like image 858
Simo D'lo Mafuxwana Avatar asked Aug 01 '13 06:08

Simo D'lo Mafuxwana


1 Answers

You're trying to set an event handler on elements that aren't in the DOM tree yet.

You can either go angular way and add ng-click:

<p ng-click="doSomething()" ng-repeat="n in ['Human or Lemar King?','Name of your tribe?','Can you Boogie?'] | filter:query" class="question"> {{n}}</p>

Or you can set a live event on <body> (or on a closer parent of the element that is present in the DOM):

$(function () {
  $('body').on('click', '.question', function() {
     alert("Ohh hail King Julien!")
  });      
});
like image 161
meze Avatar answered Nov 15 '22 05:11

meze