-1

I have a jquery event that I want to occur only after a certain amount of time. Apparently, delay only works with animation events. Is there an alternative to delay I can use in this situation?

$( document ).ready(function() {
  $(".opacity").delay(1000).css({"opacity": ".5",}).delay(1000).css({"opacity": "1",});
});
Joe Morano
  • 1,365
  • 9
  • 45
  • 108

1 Answers1

2

You can use setTimeout(), no need to use the delay function

$(document).ready(function() {
  setTimeout(function() {
    $(".opacity").css({
      "opacity": ".5",
    });
    setTimeout(function() {
      $(".opacity").css({
        "opacity": "1",
      })
    }, 1000)
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="opacity">opacity</div>

If you want to use the delay function, then you can add an entry to the delay queue using .queue() add your code there

$(document).ready(function() {
  $(".opacity").delay(1000).queue(function(next) {
    $(this).css({
      "opacity": ".5",
    })
    next();
  }).delay(1000).queue(function(next) {
    $(this).css({
      "opacity": 1,
    })
    next();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="opacity">opacity</div>
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520