Back to top button does not shake when display:none

Viewed 210

I have done a back to top button in jQuery,

      $(window).scroll(function () {
    if ($(this).scrollTop() > 50) {
      $('.back-to-top').slideDown();
    } else {
      $('.back-to-top').slideUp();
    }
  });


  // scroll body to 0px on click
  $('.back-to-top').click(function () {
    $('.back-to-top').tooltip('hide');
    $('body,html').animate({
      scrollTop: 0
    }, 800);
    return false;
  });
  $('.back-to-top').tooltip('show');

it slides down and up when scrolled, BUT now I would like it to shake (4-5 times) from time to time when it is visible. Unfortunately when in my css I make - display:none (so it does not appear when the page is loaded) - it does not shake after it appears when scrolled. Why?

.back-to-top {
  background: url(img/gruszka.png);
  width: 70px;
  height: 70px;
  background-size: 70px 70px;
  background-repeat: no-repeat;
  cursor: pointer;
  position: fixed;
  bottom: 20px;
  right: 20px;
  display:none;
  border: none;

When I delete display:none it is working and shaking. But I like the effect of sliding when I scroll... So I have made a change in jquery:

      $(window).scroll(function () {
    if ($(this).scrollTop() > 50) {
      $('.back-to-top').slideDown();
      $(".back-to-top").effect( "shake"); //I added this line
    } else {
      $('.back-to-top').slideUp();
    }
  });

and now it appears when scrolled and shakes but does not want to hide, so what should I do either in css to start shaking when scrolled OR in jQuery to go down when scrolled and stop shaking. Thank You for Your help. If its possible I would like You you to give to options how to solve it one in css and the other in jQuery.

1 Answers

Updated with Interval

You can use the following shake class and add it to the div after some delay and vice versa.

setInterval(function() {
  document.querySelector('.shake').classList.toggle("shaking");

}, 1000);
div {
  background: red;
  width: 120px;
  height: 50px;
}

.shaking {
  animation: shake 0.82s cubic-bezier(.36, .07, .19, .97);
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<div class="shake"></div>

Related