0

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!

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

this way does not work, but that previous does if I add !important for adding background to .icon-cont, since I have a background set for .icon-cont. But its much better anyway. Will try to get rid of that !important

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.