How can I determine the direction of a jQuery scroll event?

In this tutorial, we'll learn how to get the direction of a jQuery Scroll Event?
Submitted by Pratishtha Saxena, on July 22, 2022

When a webpage is created, we can determine the value of the scroll event using jQuery's scrollTop() and scrollLeft() Methods.

These two methods will help us to get the current position of the scroll bar on the webpage.

jQuery scrollTop() Method

It is an inbuilt jQuery method. It is used to get the value of the position of the vertical scrollbar for the selected elements. We can select any DOM element and get its position relative to the scrollbar.

Syntax:

$(selector).scrollTop(position);

Apart from returning the value of the scrollbar, it can also be used to set the scrollbar value for the element. The position here is mentioned when we want to set the value of the selected element on the webpage.

jQuery scrollLeft() Method

It is same as scrollTop() method. The difference is that scrollLeft() will return or set the value of the horizontal scrollbar of the webpage. The syntax and working is same as the above.

Syntax:

$(selector).scrollLeft(position);

Example:

HTML:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <div class="box"></div>
   </body>
</html>

CSS:

<style>
   html, body {
        height: 150%;
        width: 150%;
    }

    .box {
        position: fixed;
        margin: 20px;
        padding-left: 10px;
        padding-top: 10px;
        height: 15%;
        width: 15%;
        background: #e0edc2;
        font-weight: bold;
        text-align: center;
    }
</style>

jQuery:

<script>
    $(document).ready(function(){
        $(window).scroll(function(){
            $('.box').html('');
            $('.box').append("Top: "+ $(window).scrollTop());
            $('.box').append("<br>Left: "+ $(window).scrollLeft());
            console.log($(window).scrollTop());
        });
    });
</script>

Output:

Example: Determine the direction

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.