Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Rails 5, jQuery, add event to dynamically created items

I have my solution working, but I believe there would be a better, more elegant way. Any ideas are very welcome.

The thing is that navbar dropdown menu items has icons left to it. I placed icon and item name in separate spans so I could style them separately. I also wrapped those with a div, since I need to change background color of both - icon and list item name if hovered.

Navbar renders links in dropdown menu:

      <ul class="dropdown-menu">
        <% @categories.each do |cat| %>
          <li>
            <%= link_to cat do %>
            <div class="main-cont"><span id="icon-cont"><i class="glyphicon glyphicon glyphicon-tag"></i></span><span id="name-cont"><%= cat[:name] %></span></div>
          </li>
          <% end %>
        <% end %>
      </ul>

jQuery to change the background:

$(document).ready(function(){
  $('.main-cont').on('mouseover', function(){
    $(this).find('#icon-cont').css('background-color', 'yellow');
    $(this).find('#name-cont').css('background-color', 'yellow');
  });
  $('.main-cont').on('mouseout', function(){
    $(this).find('#icon-cont').css('background-color', '');
    $(this).find('#name-cont').css('background-color', '');
  });
});

So it does the job, but especially jQuery part is a bit clumsy (HTML is also far away from "wow"). Any ways to improve it? Thanks!

Upvotes: 0

Views: 89

Answers (1)

Satpal
Satpal

Reputation: 133423

As you are creating element in loop with same id i.e. icon-cont and name-cont, it create duplicate identifiers, In HTML identifiersmust be unique.

You can achieve it using pure CSS.

.main-cont:hover  {
  background-color: yellow
}
<ul class="dropdown-menu">
  <li>
    <div class="main-cont"><span class="icon-cont">loren icon<i class="glyphicon glyphicon glyphicon-tag"></i></span><span class="name-cont">loren name</span>
    </div>
  </li>
 <li>
    <div class="main-cont"><span class="icon-cont">ipsum icon<i class="glyphicon glyphicon glyphicon-tag"></i></span><span class="name-cont">ipsum name</span>
    </div>
  </li>
</ul>

Upvotes: 1

Related Questions