Home » Javascript » Determined where clicked on Vertical or Horizontal Scroll bar in my web page

Determined where clicked on Vertical or Horizontal Scroll bar in my web page

Posted by: admin November 1, 2017 Leave a comment

Questions:

Is there a way to determine if a user has clicked on specifically the horizontal scroll bar or the vertical scroll bar (considering also whether the user is dragging it or not). I want to be able to use this information to do certain things on my web page.

Answers:

A quick test in FireFox, the scroll bar created by the browser itself is not a part of the rendered HTML or DOM.

$(function() {
  $("*").click(function(e) {
    console.log(e.target);
  }).scroll(function(e) {
    console.log(e.target);
  });
});

https://jsfiddle.net/Twisty/4ow21vp6/

So you can see that a click event is not triggered. It does not even allow a right-click to Inspect the scroll bar. So detecting a ‘click’ upon these will be impossible. Other events can help though.

Questions:
Answers:

You can use scroll event to detect the movement of scrollbar and find if the user is going up/down/left/right.

var lastScrollTop = 0;
var lastScrollLeft = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st;
   
   var documentScrollLeft = $(this).scrollLeft();
   if (documentScrollLeft>lastScrollLeft){
      // scroll right code
   }else{
      // scroll left code
   }
});