I am currently using http://instantclick.io, however the plugin is not binding my dynamically created links.
PHP Response
$json['alert'] = array(
'type' => 'success',
'content' => 'Success! Your new thread has been posted, you can visit it <a href="' . site_url_in . 'forums/thread/' . $id . '">here</a>'
);
jQuery form handler
$.post(url, form, function(data){
//Lets do awesomeness
console.log('Data: ' + data);
console.log('Form: ' + form);
dm.commander.init(data);
});
Commander.init reads in the response, and the response above would execute the alert()
function within dm.commander
alert: function(message)
{
$("#messages").empty();
$("#messages").prepend('<div class="alert alert-'+message['type']+'">'+message['content']+'</div>');
// this.scrollTo('messages');
},
As you can see the PHP response sends out an alert with a link in it. The form then processes it and returns alert() which prepends a div to #messages
And the jQuery that binds is
$(document).one('click', 'a', function(e) {
console.log('clicked');
e.preventDefault();
})
InstantClick.init(100);
The above works with normal links that are already on the page however it doesn't work with the link PHP generates and jQuery prepends.
Though I cannot specifically delegate to #messages
due to other functions in the future could append to say #content
.
Is there anyway to bind instantclick to dynamically created links such as above.
And yes I have researched and couldn't find an answer that worked.
You are only initializing the InstantClick on page load. It will then apply itself on all the link currently in the DOM tree. Then when you add new links to the DOM tree, these are not automagically added to the InstantClick. Try initializing the InstantClick at the end of the AJAX alert function.
After reading NoGray's answer I think you do want to change from .one to .on. Also, this needs to be reinitiated as well:
alert: function(message)
{
$("#messages").empty();
$("#messages").prepend('<div class="alert alert-'+message['type']+'">'+message['content']+'</div>');
// this.scrollTo('messages');
$(document).unbind('click').on('click', 'a', function(e) {
console.log('clicked');
e.preventDefault();
});
InstantClick.init(100);
},
I got to admit this feels a bit dirty. Just initializing it again, but I couldn't find any documentation about some sort of destroy or reinit functions. So this is my best guess.
The original bottom code fixed:
$(document).on('click', 'a', function(e) {
console.log('clicked');
e.preventDefault();
});
InstantClick.init(100);
actually for dynamically created DOM elements you need to use on instead of one.
$(document).off("click",'a').on('click', 'a', function(e) {
console.log('clicked');
e.preventDefault();
});
thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With