0

Feeling stupid here. The .click() function is not firing and I have no idea why not. The code is really as simple as below. Note: the spans in the .selector-book div are dynamically loaded by a previous function. Any help is appreciated, as always.

HTML:

<div id="selector-book" class="selector-book">
    <span class="book-name" data-book-number="0"></span>
    <span class="book-name" data-book-number="1"></span>
    <span class="book-name" data-book-number="2"></span>
    <span class="book-name" data-book-number="3"></span>
    ...
</div>

JS:

$(document).ready(function() {
    $('.selector-book span').click(function() {
        console.log('test');
        $('.selector-chapter').html('');
        var p = $(this).data('book-number');
        for (var i = 0; i < myBible[p][2]; i++) {
            $('.selector-chapter').append('<span>' + i + '</span>');
        }
    });
});
preahkumpii
  • 1,301
  • 4
  • 21
  • 36
  • If I just use `$('.selector-book').click()` the function fires, but not with `span` as a child in the selector. – preahkumpii Aug 16 '14 at 12:18

2 Answers2

2

Because of spans are dynamically loaded, So at the time the script is being loaded, the elements are not present in DOM, that's why it doesn't bind the events with elements.

For dynamically loaded elements you have to use delegation like bellow

$('.selector-book').on('click','span',function() {..});
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
1
$(document).ready(function() {
    $('.selector-book').on('click', 'span', function() {
        console.log('test');
        $('.selector-chapter').html('');
        var p = $(this).data('book-number');
        for (var i = 0; i < myBible[p][2]; i++) {
            $('.selector-chapter').append('<span>' + i + '</span>');
        }
    });
});

Use event delegation method for dynamically generated elements.

RGS
  • 5,131
  • 6
  • 37
  • 65