JS function reload when item load with AJAX

$('#followUser').click(function () { var userId = $(this).attr('data-userId'), action = $(this).attr('data-action'), currentUser = $(this).attr('data-currentUserId'), elem = $(this); $.ajax({ method: 'POST', url: "/sci-profile/profile/follow", data: { userId: currentUser, profileUserId: userId, action: action }, success: function(response) { elem.parent().load(window.location.href + ' #unFollowUser'); } }); }); 

After clicking the button, JS loads the new div with all the contents, which is good, but the problem starts from the moment the new div is loaded.

JS does not recognize the new ID . And when I press the new button, nothing happens because the JS function is loaded when the new element does not exist.

Is there a way to make some kind of listener to check the loads of the new DIV , and then load also the JS function corresponding to this ID element?

0
source share
2 answers

YES, I did it.

This is html

  <div class="follow"> {% if followsId == null %} <div id="followUser" data-userId="{{ profileUserData.id }}" data-currentUserId="{{ loggedUserData.id }}" data-action="follow"> Follow </div> {% else %} <div id="unFollowUser" data-followsId="{{ followsId }}" data-action="unFollow"> Unfollow </div> {% endif %} </div> 

And there is JS code

 $('.follow').delegate('div', 'click', function(){ action = $(this).attr('data-action'); elem = $(this); if (action == 'follow'){ var userId = $(this).attr('data-userId'), currentUser = $(this).attr('data-currentUserId'); $.ajax({ method: 'POST', url: "/sci-profile/profile/follow", data: { userId: currentUser, profileUserId: userId, action: action }, success: function(response) { elem.parent().load(window.location.href + ' #unFollowUser'); } }); } if (action == 'unFollow'){ var followsId = $(this).attr('data-followsId'); $.ajax({ method: 'DELETE', url: "/sci-profile/profile/unFollow", data: { followsId: followsId }, success: function(response) { elem.parent().load(window.location.href + ' #followUser'); } }); } }); 

Hope this helps someone.

0
source

You should use a delegate

For example, you have this markup

 <div id=contentWrapper> .....some content here.... <button type=button id=followUser></button> </div> 
  • #contentWrapper - static block
  • everything inside is dynamic content

Now you must link your event this way

 $('#contentWrapper').on('click', '#followUser' 'function () { ...code here... }); 
+1
source

All Articles