Badger
Badger

Reputation: 487

Change state of link in jQuery

I have an ajax function that has two outcomes depending on the class of the link clicked.

I don't want to reload the whole page when the link is clicked, so I have used:

This all works except as far as jQuery is concerned, it appears as if it still has the original class, so clicking on it again, just refires the "shortlist-add" script instead of the "shortlist-remove" script.

<button data-propref="261" id="prop-261" class="btn-round btn-favorite shortlist-remove"><span class="icon-hearth"></span></button>

// remove property from shortlist
jQuery('.shortlist-remove').on('click',function() {

    var propref = jQuery(this).data('propref');

    jQuery.ajax({
        url : ajax_object.ajax_url,
        type : 'post',
        data : {
            action : 'shortlist_rem',
            propref : propref
        },
        success : function( response ) {
            jQuery('.personal-nav').load(document.URL +  ' .personal-nav');
            jQuery('#prop-' + propref).removeClass('shortlist-remove').addClass('shortlist-add');
        }
    });
});

Upvotes: 0

Views: 616

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Use a class that stays all the time as your main selector.

Then use conditionals based on the other 2 classes to change behaviors...in this case switching the action.

Then toggle the classes in the success handler

$('.btn-favorite').on('click', function(e) {
  var $btn = $(this),
    isRemove = $btn.hasClass('shortlist-remove'),
    propref = jQuery(this).data('propref');

  jQuery.ajax({
    ....
    data: {
      // action determined by classes
      action: isRemove ? 'shortlist_rem' : 'shortlist_add',
      propref: propref
    },
    success: function(response) {

      // toggle the classes now that ajax successful
      $btn.toggleClass('shortlist-remove shortlist-add');

      // other stuff
    }
  });

})

Upvotes: 1

Related Questions