Rushil K. Pachchigar
Rushil K. Pachchigar

Reputation: 1321

Click event doesn't work after append

I want to dynamic click on first click of paragraph but its not working.

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>

js Fiddle

Upvotes: 1

Views: 5079

Answers (3)

mp77
mp77

Reputation: 428

You are doing everything correct except one thing - You are declaring event handler of your second click after the click itself. So, when second click is triggered, you don't have handler declared yet and you don't see any alert. I rearranged it below. Trying running the below snippet.

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);
      
      //on click event handler should be declared first before clicking
     $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    
    $(".hrefclick").click();

   
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>

Upvotes: 0

Rafael Umbelino
Rafael Umbelino

Reputation: 810

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    $('.hrefclick').trigger('click');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>

Upvotes: 0

DaniP
DaniP

Reputation: 38262

You need to trigger the click() after the delegation, just change the order of your lines:

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    $(".hrefclick").click();
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>

Upvotes: 4

Related Questions