Delaying a click function in jQuery

Viewed 62

I have a click function that when a link is clicked, the scrolls down to the attached div. How do I attach a delay of about 5seconds before it actually scrolls down?

I have tried to add .delay() to the function but it doesn't seem to work

$(".o-c").click(function() {
  $('html, body').animate({
    scrollTop: $(".one").offset().top
  }, 2000);
});
.left {
  width: 50%;
  float: left;
  background: red;
  height: 100vh;
}

.right {
  width: 50%;
  float: right;
  background: green;
  height: 100vh;
}

.one {
  width: 100%;
  background: yellow;
  height: 100vh;
  display: block;
  clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="left">


  <ul class="pivot-nav">
    <li class="pivot-nav-item"><a class="o-c default-underline custom-scroll-link" href="#one" data-toggle="my-scrollspy-2">1</a></li>


  </ul>

</div>



<div class="one">
  Some more TEXT HERE
</div>

2 Answers

You can call delay() to add a pause before an animation runs on the fx queue:

$(".o-c").click(function() {
  $('html, body').delay(5000).animate({
    scrollTop: $(".one").offset().top
  }, 2000);
});

$(".o-c").click(function() {
  $('html, body').delay(5000).animate({
    scrollTop: $(".one").offset().top
  }, 2000);
});
.left {
  width: 50%;
  float: left;
  background: red;
  height: 100vh;
}

.right {
  width: 50%;
  float: right;
  background: green;
  height: 100vh;
}

.one {
  width: 100%;
  background: yellow;
  height: 100vh;
  display: block;
  clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="left">
  <ul class="pivot-nav">
    <li class="pivot-nav-item"><a class="o-c default-underline custom-scroll-link" href="#one" data-toggle="my-scrollspy-2">1</a></li>
  </ul>
</div>
<div class="one">
  Some more TEXT HERE
</div>

Alternatively you can use setTimeout():

$(".o-c").click(function() {
  setTimeout(function() {
    $('html, body').animate({
      scrollTop: $(".one").offset().top
    }, 2000);
  }, 5000);
});

You can use setTimeout() for delay.

$(".o-c").click(function() {
  setTimeout(function(){
  $('html, body').animate({
    scrollTop: $(".one").offset().top
  }, 2000);
},2000);})
.left {
  width: 50%;
  float: left;
  background: red;
  height: 100vh;
}

.right {
  width: 50%;
  float: right;
  background: green;
  height: 100vh;
}

.one {
  width: 100%;
  background: yellow;
  height: 100vh;
  display: block;
  clear: both;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<div class="left">
  <ul class="pivot-nav">
    <li class="pivot-nav-item"><a class="o-c default-underline custom-scroll-link" href="#one" data-toggle="my-scrollspy-2">1</a></li>
  </ul>
</div>
<div class="one">
  Some more TEXT HERE
</div>

Related