Morteza Ziyaeimehr
Morteza Ziyaeimehr

Reputation: 2117

jQuery functions don't work on the elements created 'on the fly'

I created some elements on the fly by JavaScript like this:

tmpString += '<a class="small_text add" id="' + variable_id + '_add" href="#" > add </a>';
$('#mydiv').html(tmpString);

Problem

jQuery functions don't work on these 'on the fly' elements, but the same jQuery functions work on other normal elements (like "a" tags in my site menu).

This is my jQuery code:

$('a').click(function(){ e.preventDefault(); alert(1); });

Upvotes: 0

Views: 378

Answers (3)

Tomalak
Tomalak

Reputation: 338178

Use live() for elements that you add dynamically.

$('a').live("click", function(e){ e.preventDefault(); alert(1); });

Upvotes: 1

The click handler should be recalled everytime you create elements on-the-fly.

Upvotes: 0

Sahil Muthoo
Sahil Muthoo

Reputation: 12519

You need to use live or delegate.

$('a').live('click', function() {
    //your code
});

Upvotes: 6

Related Questions