Ricky Mason
Ricky Mason

Reputation: 1828

How do get the clicked object when using a Rails UJS "remote: true" ajax link?

I wanted to add a simple Star icon for favorites, however it became difficult when I wanted to use JS's this object to change the star icon from class star to star-o and vice versa.

I ended up just assigning a unique Id for each area that had a favorite icon...but this seemed overly difficult when dealing with pages that have dynamic content.

Is there anyway to reference the element you clicked while using remote:true and ajax through rails?

Upvotes: 0

Views: 1023

Answers (1)

max
max

Reputation: 101811

jQuery Rails fires a "ajax:success" event on the triggering element when you use data-remote:

$(".favorite").on("ajax:success",function(e, data, status, xhr){
  $(this).addClass('star-o').removeClass('star');
});

Adapted from Working with JavaScript in Rails.

Upvotes: 3

Related Questions