Reputation: 1600
I'm working on a +Follow function for a profile in my app. Follow functionality works just once (on a fresh page load), but after the script replaces DOM elements, it doesn't work.
HTML output when a profile is not being followed by user:
<div id="follow">
<a>Follow profile</a>
</div>
HTML output When a profile is currently followed by user:
<div id="unfollow">
<a>Unfollow profile</a>
</div>
The magic happens in jQuery. The following function is wrapped in a $(document).ready()
function:
function follow() {
$("#follow a").on("click", function() {
// $.getJSON fn here that follows profile and returns success T/F
if ( success ) {
$("#follow").remove();
$("#follow-container").html('<div id="unfollow"><a>Unfollow profile</a></div>');
}
});
$("#unfollow a").on("click", function() {
// $.getJSON fn here that unfollows profile and returns success T/F
if ( success ) {
$("#unfollow").remove();
$("#follow-container").html('<div id="follow"><a>Follow profile</a></div>');
}
});
}
Suppose a user clicks "Follow profile". The script removes the #follow a
link and replaces it with a #unfollow a
link. However, the JS script which runs when #unfollow a
is clicked doesn't execute because this element was added to the DOM after page load.
To solve this, I tried to refresh the function like this:
if ( success ) {
$("#follow").remove();
$("#follow-container").html('<div id="unfollow"><a>Unfollow profile</a></div>');
// reload function
follow();
}
This doesn't work. The unfollow click event is not registered. How else do I reload the DOM in this case?
Upvotes: 3
Views: 8108
Reputation: 44740
Use event delegation -
$("#follow-container").on("click","#follow a", function() {
and
$("#follow-container").on("click","#unfollow a", function() {
Also : you have a typo here $(#follow-container")
this should be $("#follow-container")
Upvotes: 7