Olie Ayre Olie Ayre - 7 months ago 18
HTML Question

JQuery: Make hovered <li> move

I have a series of lists on my webpage and I'm trying to use JQuery to have these list items move to the side a bit when hovered over. This is what I have so far and it doesn't work:

HTML

<ul>
<li><div>&nbsp;</div>Text1</li>
<li><div>&nbsp;</div>Text2</li>
<li><div>&nbsp;</div>Text3</li>
</ul>


JQuery

$(document).ready(function() {
$("li").hover(function() {
$("div").animate({
width: '+=10px'
});
}, function() {
$("div").animate({
width: '-=10px'
});
});
});


CSS

div {
width : 0px;
display : inline-block;
}


Here's a JSFiddle: https://jsfiddle.net/mjpcr9ov/

Answer

There is a bug in your code and also get the div inside the li by passing it's context

$(document).ready(function() {
  $("li").hover(function() {
    $("div", this).animate({
      width: '+=10px'
    });
  }, function() {
  //        -^----- remove `)` from here
    $("div", this).animate({
      width: '-=10px'
    });
  });
});
div {
  width: 0px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>
    <div>&nbsp;</div>Text1</li>
  <li>
    <div>&nbsp;</div>Text2</li>
  <li>
    <div>&nbsp;</div>Text3</li>
</ul>


UPDATE : Demo with nested span inside
$(document).ready(function() {
  $("li span").hover(function() {
    $(this).parent().find("div").animate({
      width: '+=10px'
    });
  }, function() {
    $(this).parent().find("div").animate({
      width: '-=10px'
    });
  });
});
div {
  width: 0px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>
    <div>&nbsp;</div><span>Text1</span>
  </li>
  <li>
    <div>&nbsp;</div><span>Text2</span>
  </li>
  <li>
    <div>&nbsp;</div><span>Text3</span>
  </li>
</ul>