Wesly
Wesly

Reputation: 343

How to use javascript to make 2 different button show without browser refresh

I have never been too good with javascript and i cant seem to get any of the tutorials that I've found . I have a button that favorites and un-favorites. I would like it if someone clicks on the favorite button that the un-favorite button shows up without the browser refreshing and so on if they click on the un-favorite button.

Favorite button

<button class="follow"><%= link_to "un-Favorite", unfavorite_anime_path(anime), method: :put%></button>

Un-favorite button

 <button class="follow"><%= link_to "Favorite", favorite_anime_path(anime), method: :put%></button>

Controller

def favorite
    if @anime = Anime.all
        current_user.mark_as_favorite @anime
        redirect_to @anime = :back
    elsif @amime = Anime.friendly.find(params[:id])
        current_user.mark_as_favorite @anime
    end
end

def unfavorite
    @anime = Anime.friendly.find(params[:id])
    @anime.unmark :favorite, :by => current_user
    redirect_to @anime = :back
end

Upvotes: 0

Views: 52

Answers (1)

elzi
elzi

Reputation: 5672

1) Add remote: true in your link_to

2) Give the buttons IDs of #follow and #unfollow, then use the JS:

$('.follow').click(function (event) {
  $('#follow, #unfollow').toggle()
})

Provided that one of them is initially set to display:none

Upvotes: 1

Related Questions