FlowCastv
FlowCastv

Reputation: 147

jQuery onClick function didn't work after change of id

I'm creating follow button using AJAX in Laravel. When I click follow, it will turn into unfollow with the change of id. I tried to click unfollow button again, it didn't execute unfollow on click function but remain the previous follow on click function.

HTML

 <a id="followAnchor" type="submit" class="btn btn-info" /><i class="fa icon-user-follow"></i> Follow</a>
                                                                     </div>

AJAX

$('#followAnchor').on("click", function(e){
var followId = document.getElementById('followAnchor');
 $.ajax({
          url: "{{ URL::route('follow-post') }}",
          type: 'POST',
          data: JSON.stringify(arr),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
    }).done(function(response) {

          if(response.errors)
          {

          }
          else if (response.success){


            followId.innerHTML = "<i class='fa icon-user-follow'></i>" + "Unfollow";
            document.getElementById('followAnchor').id = 'unfollowAnchor';
          }
    });
}

$('#unfollowAnchor').on("click", function(e){
    var unfollowId = document.getElementById('unfollowAnchor');

    $.ajax({
          url: "{{ URL::route('unfollow-post') }}",
          type: 'POST',
          data: JSON.stringify(arr),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
    }).done(function(response) {

          if(response.errors)
          {

          }
          else if (response.success){
            unfollowId.innerHTML = "<i class='fa icon-user-follow'></i>" + "Follow";
            document.getElementById('unfollowAnchor').id = 'followAnchor';
          }
    });
});

Upvotes: 1

Views: 1042

Answers (2)

empiric
empiric

Reputation: 7878

You need to use event-delegation, because you are register a event-listiner on an element that not exist by that time.

$('#unfollowAnchor').on("click", function(e){

has to be

$(document).on("click", '#unfollowAnchor',function(e){

Instead of using IDs here, I would go with adding or removing specific classes:

$(followId).addClass('unfollow').removeClass('follow');

as an example.

Upvotes: 1

epascarello
epascarello

Reputation: 207527

Events do not magically get bound after they are changed. Once the code has run it does not keep checking for new elements.

  • You either need to unbind/bind the event when you change the id/ add new elements.
  • Do not change the id, just add logic into the original click (what most devs do)
  • Or use event bubbling.

Bubbling example:

$(document).on("click", "#followAnchor", function(e){ /* code here */ });        
$(document).on("click", "#unfollowAnchor", function(e){ /* code here */ });

Upvotes: 5

Related Questions