PCA
PCA

Reputation: 1707

How to attach event to the newly added anchor using jquery

I trying to attach a click event for the newly added anchor tag(.he) after the #foo anchor tag. But the click event is not happening. I have used (.on). Can you guys help me in this ?*

        <!DOCTYPE html>
        <html>
        <head>
        <title>Attaching event</title>
       <style>p { background:yellow; margin:6px 0; }</style>
       <script src="js/jquery.js"></script>
        </head>
    <body>
    <p>Hello</p>
    how are
    <p>you?</p>

    <button>Call remove() on paragraphs</button>

    <a id="foo" href="#" style="display:block">Testing the bind and unbind</a>


    <script>
        $("button").on('click',function () {

            $("#foo").after("<a class='he' href='#'>asdfasdf</a>");

        });
        $(".he").on('click', function(){
                alert("test");
        });     

    </script>
</body>

Upvotes: 2

Views: 707

Answers (6)

steveukx
steveukx

Reputation: 4368

You can either attach a handler to the anchor directly before it is appended into the document:

$("button").on('click',function () {
   $("<a class='he' href='#'>asdfasdf</a>")
      .on('click', function(){
         alert("test");
      })
      .insertAfter("#foo");
});

or bind a delegate handler on the document that will catch all clicks on anchors with he as their class:

$(document).on('click', 'a.he', function() {
   alert("test");
});
$("button").on('click',function () {
   $("<a class='he' href='#'>asdfasdf</a>").insertAfter("#foo");
});

Upvotes: 0

Fisch
Fisch

Reputation: 3815

You can instead bind the click event to the anchor before appending it to the DOM like this:

 var $he = $("<a class='he' href='#'>asdfasdf</a>").on('click', function(){
                 alert("test");
            })
 $("#foo").after($he);

Upvotes: 0

user2063626
user2063626

Reputation:

you will have to put the below code inside $("button").click block.

  $(".he").on('click', function(){
                    alert("test");
            }); 

Link for jsfiddle http://jsfiddle.net/wbWLE/

Upvotes: 0

novalagung
novalagung

Reputation: 11512

use .live. and don't forget to add your code inner jquery clousure

<script>
    $(function(){
        $("button").on('click',function () {
            $("#foo").after("<a class='he' href='#'>asdfasdf</a>");
        });

        $(".he").live('click', function(){
            alert("test");
        });
    });
<script>

Upvotes: 0

VisioN
VisioN

Reputation: 145428

Use event delegation

$("body").on("click", ".he", function() {
    alert("test");
});

Instead of body you can use any static parent element of .he.

Upvotes: 0

Anton
Anton

Reputation: 32581

You have to delegate to a static parent element like this

$(document).on('click','.he',function(){

//code here
});

Upvotes: 5

Related Questions