كيفية اضافة button في الصفحة للذهاب لاول الصفحه Go to top باستخدام scrollTop

تطوير الويب Backend - Javascript

بنتعلم في هذا المقال كيف ممكن نضيف button في الصفحة للذهاب لاول الصفحه Go to top باستخدام scrollTop. وهذا button يعرض في الصفحة لما يكون محتوي الصفحه طويل للاسفل. فا بدل ما نرجع بالفأرة لفوق ممكن نستخدم هذا Button  

للتوضيح: 

بكون شكل button مثل الموقع الحالي اذا نزلت لاسفل الصفحة اكيد بتشوف button التالي:

عند النقر على هذا button بترجع الصفحه للاعلي.

تمام نفهم كيف بنعمل هذا الكلام. 

في البداية بنضيف button  في الصفحه (المكان مش مهم) لانو بنتحكم بالمكان عن طريق CSS

نضيف الكود التالي :

 <button onclick="topFunction()" id="myBtn" title="Go to top">
<i class="fa fa-arrow-up" aria-hidden="true"></i>
</button>

بعد هيك اضفنا كود CSS باستخدام Id الخاص ب button الي هو myBtn

الكود:

#myBtn {
    display: none;
    position: fixed;
    bottom: 20px;
    left: 30px;
    z-index: 99;
    font-size: 18px;
    border: none;
    outline: none;
    background-color: darkolivegreen;
    color: white;
    cursor: pointer;
    padding: 10px;
    border-radius: 2px;
}

عرفنا في هذا الكود حجم ولون button والمكان والخصائص الثانيه المسؤوله عن عرض button بالشكل في الصورة

وحتى يشتغل هذا الحكي لازم نضيف كود JavaScript الى الصفحه

اضف الكود التالي: 

//Get the button
    var mybutton = document.getElementById("myBtn");
    // When the user scrolls down 20px from the top of the document, show the button
    window.onscroll = function () { scrollFunction() };
    function scrollFunction() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            mybutton.style.display = "block";
        } else {
            mybutton.style.display = "none";
        }
    }
    // When the user clicks on the button, scroll to the top of the document
    function topFunction() {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    }

في هذا الكود عملنا في البداية متغير باسم mybutton الي من خلالو وصلنا الي button في الصفحه.

بعد هيك طبقنا الكود التالي 

    window.onscroll = function () { scrollFunction() };
    function scrollFunction() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            mybutton.style.display = "block";
        } else {
            mybutton.style.display = "none";
        }
    }

هذا الكود هو كود JavaScript بشتغل لما نعمل scroll للصفحه، وبنعمل فحص اذا نزل المستخدم في الصفحة بمقدار 20px  من الاعلى بتم عرض هذا button وغير ذلك بتم اخفاء button 

الكود الاخير هو الكود المسؤول عن ارجاع المستخدم الى بداية الشاشة 

الكود:

 function topFunction() {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    }