Search code examples
cssruby-on-railshoverlink-tomousehover

Show content on link_to using hover (rails)


Currently I have a link_to that when clicked it opens a popup. I want to add a function so that when I hover on the link it shows certain content. I want to show the users who liked a post similar to facebook likes when you mouseover.

Upon hover I want to show who liked the post via

render micropost.voters_who_voted

microposts/_micropost:

<%= link_to into_it_micropost_path(micropost.id), :onclick => "javascript:window.open('/microposts/#{micropost.id}/into_it','popup','width=285,height=300,top=315,left=200');", id: "feeditemlikes_#{micropost.id}", remote: true do %>
  <%= "#{micropost.votes_for} Into it!" %>
    <ul class="likes">
      <%= render micropost.voters_who_voted %>
    </ul>
<% end %>

CSS:

[id^=feeditemlikes] {
  .likes { display: none; }
  &:hover {
    text-decoration: none;
    color: $blue;
    .likes { display: block; }
}

}


Solution

  • If you want to show certain content on hover using CSS, then that content must be a child element of the element that receives :hover (in this case the link). For example:

    ERB:

    <%= link_to into_it_micropost_path(micropost.id), :onclick => "javascript:window.open('/microposts/#{micropost.id}/into_it','popup','width=285,height=300,top=315,left=200');", id: "feeditemlikes_#{micropost.id}", remote: true do %>
      <%= "#{micropost.votes_for} Into it!" %>
      <ul class="users">
        <%= render @user.names %>
      </ul>
    <% end %>
    

    SCSS:

    [id^=feeditemlikes] {
      .users { display: none; }
      &:hover {
        text-decoration: none;
        color: $blue;
        .users { display: block; }
      }
    }
    

    (By the way, instead of using [id^=feeditemlikes], I would put a class on the link and refer to that. See below.)

    But if you want to show content on hover that is not a child element of the link, then you need to use JavaScript.

    Here's an example using CoffeeScript and jQuery:

    $('a.feed-item-likes').hover ->
      $('.users').toggle()