Reputation: 1321
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>
Upvotes: 1
Views: 5079
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
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
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