javascript - Rails 4: Upvote/Downvote with coffeescript -


it's similar here on stackoverflow- can upvote comment , when marked orange arrow. however, have 2 icons(on & off) upvote , 2 downvote. problem when click on upvote, changes icon 'on', good, when click on downvote after that, upvote stays same(with on icon). so, 2 'on' icons.

the goal: when upvote/downvote , decide change vote, icon previous choice should 'off'

-my current code-

<div class="thumbsup">     <%= link_to image_tag('othericons/thumbsup_off.png', height: '20', width: '20', id: "imgclickandchange", :onclick => "window.changeimage($(this))"),  like_post_comment_path(comment.post_id, comment), method: :put, :remote => true %> </div>  <div class="thumbsdown">   <%= link_to image_tag('othericons/thumbsdown_off.png', height: '20', width: '20', id: "imgclickandchange", :onclick => "window.toggleimage($(this))"), dislike_post_comment_path(comment.post_id, comment), method: :put, :remote => true %> </div> 

coffeescript

window.changeimage = (source) ->     console.log "called changeimage(source)"     $source = $(source)     imagepath = $source.attr("src")     if imagepath && imagepath == "/assets/othericons/thumbsup_off.png"       console.log "thumbsup off"       $source.attr("src", "/assets/othericons/thumbsup_on.png")     else       console.log "thumbsup on"       $source.attr("src", "/assets/othericons/thumbsup_off.png")  window.toggleimage = (source) ->     console.log "called changeimage(source)"     $source = $(source)     imagepath = $source.attr("src")     if imagepath && imagepath == "/assets/othericons/thumbsdown_off.png"       console.log "thumbsdown off"       $source.attr("src", "/assets/othericons/thumbsdown_on.png")     else       console.log "thumbsdown on"       $source.attr("src", "/assets/othericons/thumbsdown_off.png") 

you'd better handling data server:

#app/controllers/votes_controller.rb def      #your code      status = "on"      respond_to |format|          format.js { render json: status.to_json }      end end  #same dislike, except status = "off" 

then can handle image with ajax:success callback:

$(document).on "ajax:success", "#imgclickandchange", (data) ->     $(this).attr("src"), "/assets/othericons/thumbsup_"+ data +".png") 

currently, don't know how coffeescript firing? it's not bound events?


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -