Andrew Andrew - 24 days ago 7
jQuery Question

How to preventDefault and disable a href

On first click my button click function works, but upon clicking again it refreshes the page click the unbind isn't recognized. I need to prevent any default click event as well as disable the button after click.

<a href="" class="red-btn2">Save this Property</a>

$(".red-btn2").click(function(event){
event.preventDefault();
$(this).unbind('click');
$(this).css({
'background-color':'#666666',
'text-align':'center'
});
$(this).text("Added to Favorites");
});

Answer

If you need the rest of the handler to run only once, but preventDefault() always, you can separate them into multiple handlers.

Then, one of them can be removed after its first use (using jQuery's .one() will cover that for you), still leaving the preventDefault() in use:

$('.red-btn2')
    .click(function (event) {
        event.preventDefault();
    })
    .one('click', function () {
      $(this).css({
        'background-color':'#666666',
        'text-align':'center'
      });
      $(this).text("Added to Favorites");
    });

As you have it, the event.preventDefault() is being removed as well by .unbind('click'), so no functions are left on the element to call it for the 2nd click.