1

I have a menu and each list item gets a different color border on hover. It works but it feels clunky. How can i optimize this code so I don't repeat so much.

$('ul>li:first-child>a').hover(function() {
  $(this).css('border-bottom', '0.2em solid blue');
}, function() {
  $(this).css('border-bottom', '0');
})

$('ul>li:nth-child(2)>a').hover(function() {
  $(this).css('border-bottom', '0.2em solid green');
}, function() {
  $(this).css('border-bottom', '0');
})

$('ul>li:last-child>a').hover(function() {
  $(this).css('border-bottom', '0.2em solid yellow');
}, function() {
  $(this).css('border-bottom', '0');
})
ul li {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Blue</a></li>
  <li><a href="#">Green</a></li>
  <li><a href="#">Yellow</a></li>
</ul>

1
  • 1
    meta.stackoverflow.com/a/295692/4076315 - You might get more help if you include your attempt at optimization and describe where you got stuck. Commented Jun 3, 2015 at 2:03

1 Answer 1

1

You can achieve this entirely by using CSS and HTML. Just add class to your list elements and target them using CSS style.

HTML:

<ul>
  <li class="blue"><a href="#">Blue</a></li>
  <li class="green"><a href="#">Green</a></li>
  <li class="yellow"><a href="#">Yellow</a></li>
</ul>

CSS:

ul li {
  display: inline-block;
}
.blue a:hover{
    color:#0000ff;
}
.green a:hover {
    color:#00ff00;
}
.yellow a:hover {
    color:#ffff00;
}

Check the Fiddle here: https://jsfiddle.net/rnjr1aL9/

Edit: I have CSS for text color but you can target different things like border-color, font-size, etc.

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

Comments

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.