Reputation: 1823
I want an event to be triggered after the creation of the corresponding HTML object (href
in my case).
I've written this code:
$(document).ready(function() {
$('body').on('click', '#stats-link', function(e) {
console.log('TRIGGERED'); // nothing is logged
e.preventDefault();
$.post('stats.php', {'email': $('#email').val()}, function() {
window.location = $(this).attr('href');
});
});
$('#submit_button').click(function(e) {
e.preventDefault();
...
$('#info').html('<p class="desc"><a href="stats.php" id="stats-link">bla bla bla</a></p>');
...
});
});
So, I make a href
object identified by stats-link
in the #submit_button
function, then I want him to be triggered in the corresponding function (i.e., $('body').on(...)
, but it doesn't happen. What am I doing wrong?
Upvotes: 0
Views: 68
Reputation: 18099
Did you missed this line:
$('#stats-link').trigger('click');
This will trigger the click event. The code you shared only binds the event. You need to trigger it.
JS:
$(document).ready(function () {
$('body').on('click', '#stats-link', function (e) {
e.preventDefault();
alert('clicked')
$.post('stats.php', {
'email': $('#email').val()
}, function () {
window.location = $(this).attr('href');
});
});
$('#submit_button').click(function (e) {
e.preventDefault();
$('#info').html('<p class="desc"><a href="stats.php" id="stats-link">bla bla bla</a></p>');
$('#stats-link').trigger('click'); //This is where you trigger the click.
});
});
Working Demo: http://jsfiddle.net/lotusgodkk/artaq4xj/
Upvotes: 2
Reputation: 54
Your preventDefault() parameter is lacked :
$('body').on('click', '#stats-link', function(event) {
event.preventDefault();
$.post('stats.php', {'email': $('#email').val()}, function() {
window.location = $(this).attr('href');
});
});
Upvotes: 1
Reputation: 3974
What is e
? Are you sure the click event isn't actually working, but just giving you a script error and bailing out before it does anything? Your callback function does not define the passed in event
parameter e
.
$('body').on('click', '#stats-link', function() { // <-- No e parameter supplied.
e.preventDefault(); // <---- What is e?
...
}
Upvotes: 1