javascript – I want to change the background color when the mouse over the li element

Question:

I created the following code that wants to fade and change the background color when the mouse hovers over the li element, but the animation and color changes are not reflected. Why.

 $(document).ready(function(){ $('li').hover(function(){ $(this).css("cursor", "pointer").stop().animate({backgroundColor:"#000000"}, 800); }); });
 <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <meta charset="utf-8"> <title>Hoge</title> </head> <body> <li> <p>hoge</p> </li> </body> </html>

Answer: Answer:

Normally, use CSS transition .

If you can restore the background color when you remove the mouse from the element, you no longer need JavaScript (and jQuery, of course) at all.

Try the following example.

.target li {
  transition: background-color 2s;
}

.target li:hover {
  background-color: #0f0;
  transition: background-color 800ms;
}
<ul class="target">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
  <li>Item 10</li>
</ul>
Scroll to Top