Sam Skirrow Sam Skirrow - 4 months ago 16
CSS Question

jQuery mouseover function on multiple elements with a delay

I have 3 spans wrapped in a div. When a user hovers over the dive, I want each span to move slightly to the right, with a delay of .5s between each.

Here is my current code:

$('.library_vid').mouseover(function(){
$(this).find('.lesson_meta span:nth-child(1)').css('margin-right', '30px');
setTimeout(function () {
$(this).find('.lesson_meta span:nth-child(2)').css('margin-right', '30px');
}, 500);
setTimeout(function () {
$(this).find('.lesson_meta span:nth-child(3)').css('margin-right', '30px');
}, 1000);

})


However, currently this just moves the first span, the delay never amounts to anything

Answer

$('.library_vid').mouseover(function() {
  var parent = $(this)
  parent.find('.lesson_meta span:nth-child(1)').css('margin-left', '30px');
  setTimeout(function() {
    parent.find('.lesson_meta span:nth-child(2)').css('margin-left', '30px');
  }, 500);
  setTimeout(function() {
    parent.find('.lesson_meta span:nth-child(3)').css('margin-left', '30px');
  }, 1000);
})
div {
  width: 130px;
  height: 300px;
}
span {
  height: 100px;
  width: 100px;
  display: inline-block;
}
.span1 {
  background-color: green;
}
.span2 {
  background-color: blue;
}
.span3 {
  background-color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="library_vid">
  <div class="lesson_meta">
    <span class="span1"></span>
    <span class="span2"></span>
    <span class="span3"></span>
  </div>
</div>

I think the issue was the $(this) nested within your set timeouts. Declaring it as a variable is a common 'cheat'. Also, you said you wanted to move them to the right, but were adding margin on the right

Comments