Code nút back to top

Cái nút back to top nhiều theme không có, các bạn thường cài plugin để ra cái nút này, tuy nhiên đôi lúc nhiều plugin sẽ không tốt.

Hôm nay mình xin share đoạn code để tạo ra nút back to top, các bạn chỉ cần bỏ vào file functions.php của theme đang dùng là được

//code back to top
add_action('wp_footer', 'back_to_top');
function back_to_top(){
?>
<a href="#" class="cd-top">Back To Top</a>
  <style>
    /* back to top */
    a.cd-top {
      display: inline-block;
      height: 40px;
      width: 40px;
      position: fixed;
      bottom: 25%;
      right: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
      /* image replacement properties */
      overflow: hidden;
      text-indent: 100%;
      white-space: nowrap;
      background: #3097D1 url(https://minhhien.vn/img/cd-top-arrow.svg) no-repeat center 50%;
      visibility: hidden;
      opacity: 0;
      -webkit-transition: opacity .3s 0s, visibility 0s .3s;
      -moz-transition: opacity .3s 0s, visibility 0s .3s;
      transition: opacity .3s 0s, visibility 0s .3s;
    }
    a.cd-top.cd-is-visible, a.cd-top.cd-fade-out, .no-touch a.cd-top:hover {
      -webkit-transition: opacity .3s 0s, visibility 0s 0s;
      -moz-transition: opacity .3s 0s, visibility 0s 0s;
      transition: opacity .3s 0s, visibility 0s 0s;
    }
    a.cd-top, a.cd-top:visited, a.cd-top:hover {
      color: #CCCCCC;
      text-decoration: none;
    }
    a.cd-top.cd-is-visible {
      /* the button becomes visible */
      visibility: visible;
      opacity: 1;
    }
    a.cd-top.cd-fade-out {
      /* if the user keeps scrolling down, the button is out of focus and becomes less visible */
      opacity: 1;
    }
  </style>
  <script>
      jQuery(document).ready(function($){
    // browser window scroll (in pixels) after which the "back to top" link is shown
      var offset = 300,
      //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
      offset_opacity = 1200,
      //duration of the top scrolling animation (in ms)
      scroll_top_duration = 700,
      //grab the "back to top" link
      $back_to_top = $('.cd-top');
      //hide or show the "back to top" link
      $(window).scroll(function(){
      ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
        if( $(this).scrollTop() > offset_opacity ) {
          $back_to_top.addClass('cd-fade-out');
        }
      });
      //smooth scroll to top
      $back_to_top.on('click', function(event){
        event.preventDefault();
        $('body,html').animate({
          scrollTop: 0 ,
        }, 
        scroll_top_duration
        );
      });
    });
  </script>
<?php
};

Chúc các bạn thực hiện thành công!

Recommended For You

Leave a Reply

Your email address will not be published. Required fields are marked *