xonorageous
xonorageous

Reputation: 2281

JQuery - Use selectors on generated content

I'm having problems selecting elements with jquery selectors on content generated with javascript.

For the generation I use the following function:

var articles = [
    {
        img: { src: this.base_url + 'assets/img/frontend/placeholder.png', alt: 'Image Description' },
        title : 'Title Here',
        text: 'Lorem ipsum dolor sit amet, consectetur adispiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet ' + 
              'dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci.'
    },
    {
        img: { src: this.base_url + 'assets/img/frontend/placeholder.png', alt: 'Image Description' },
        title : 'Title Here',
        text: 'Lorem ipsum dolor sit amet, consectetur adispiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet ' + 
              'dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci.'
    },
    {
        img: { src: this.base_url + 'assets/img/frontend/placeholder.png', alt: 'Image Description' },
        title : 'Title Here',
        text: 'Lorem ipsum dolor sit amet, consectetur adispiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet ' + 
              'dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci.'
    }
];

var template = Handlebars.compile( $( '#picture-above-text' ).html() );
$( 'div.editor-wrapper' ).append( template( articles ) );

This inserts the following html in the page :

<div class="row insumo-editor-module" style="display: none;">
    {{#each this}}
        <article class="span4" article-tile>
            <figure>
                <div class="figure-holder">
                    <img src="{{img.src}}" alt="{{img.alt}}">
                    <span class="figure-indicator"></span>
                </div>
                <figcaption>
                    <div class="editable"><h4>{{title}} <i class="icon-edit"></i></h4></div>
                    <div class="editable"><p>{{text}} <i class="icon-edit"></i></p></div>
                </figcaption>
            </figure>
        </article>
    {{/each}}
</div>

Up to this point there are no problems. However when I use

$( 'i.icon-edit' ).on( 'click', function() {
    alert( 'editing' );
});

nothing is happening. Does anyone know why this is happening? I guess it's because the icon wasn't on the page when the DOM was first generated. Is there any way around this?

Thanks in advance

Upvotes: 1

Views: 6421

Answers (2)

elrado
elrado

Reputation: 5272

Use jquery delegate. Klik link

Upvotes: 0

palaѕн
palaѕн

Reputation: 73896

Since the icon-edit is added dynamically, you need to use event delegation to register the event handler

// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on('click', 'i.icon-edit', function(event) {
    event.preventDefault();
    alert( 'editing' ); 
});

Upvotes: 8

Related Questions