Reputation:
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> </div>Text1</li>
<li><div> </div>Text2</li>
<li><div> </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/
Upvotes: 0
Views: 36
Reputation: 115232
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)
.stop() // use stop for strop the previous animation
.animate({
width: '+=10px'
});
}, function() {
// -^----- remove `)` from here
$("div", this)
.stop() // use stop for strop the previous animation
.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> </div>Text1</li>
<li>
<div> </div>Text2</li>
<li>
<div> </div>Text3</li>
</ul>
$(document).ready(function() {
$("li span").hover(function() {
$(this)
.prev()
// or
// .parent() // get parent li
// .find("div") // find div inside
.stop() // use stop for strop the previous animation
.animate({
width: '+=10px'
});
}, function() {
$(this)
.prev()
// or
// .parent() // get parent li
// .find("div") // find div inside
.stop() // use stop for strop the previous animation
.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> </div><span>Text1</span>
</li>
<li>
<div> </div><span>Text2</span>
</li>
<li>
<div> </div><span>Text3</span>
</li>
</ul>
Upvotes: 2