Muhammad Ali
Muhammad Ali

Reputation: 2014

Added Div not working click function

In my scenario , i have to use class to add div , this may easily solve with onClick function, but i require this to complete my task, .click(function() is not working on new element , javascript /jquery may store element onload or what???

FIDDLE

<div class="add">
  <div class="anyRow">Hello<hr/></div>
</div>



$('.anyRow').click(function(){
$('.add').append('<div class="anyRow">Hello</hr></div>')
});

Upvotes: 0

Views: 80

Answers (4)

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

For older jquery versions you can use live function if html is changed dynamically (I saw you using an older jquery version in the fiddle)

$('.add').live( 'click', function () {
    $('.add').append('<div class="anyRow">Hello</hr></div>')
});

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

If you are using in real case (as in posted jsFiddle) jQuery v1.6.4, you should use .delegate() method:

$('.add').delegate('.anyRow', 'click', function () {
    $('.add').append('<div class="anyRow">Hello</hr></div>')
});

-DEMO-

http://learn.jquery.com/events/event-delegation/

Upvotes: 1

UserDy
UserDy

Reputation: 357

The method bellow applies event handlers to elements even before they exist

$("#parent-element").on("click", "#new-element", function() {
    // your code
});

Upvotes: 0

Starmetal
Starmetal

Reputation: 760

You have to use on() method as the deprecated live() one, to delegate click for future new elements.

$(document).on("click", ".anyRow", function() {
  $('.add').append('<div class="anyRow">Hello</hr></div>');
});

Upvotes: 2

Related Questions