Trigger a global event on click and drag on the scrollbar of any scrollable container

Let me explain the problem clearly, I have a lot of containers (added dynamically) in which I have custom dropdowns. The containers are installed overflow: auto

.

This way the custom dropdowns are hidden inside these scrollable containers. To fix this I am using position: fixed

for custom dropdowns.

Now I can see the suggestions and I am using jquery to stitch those suggestions into the appropriate dropdowns. But now, when I view a specific container, the custom dropdowns are being diverted from that dropdown.

So, of course, I need to call this line function again when scrolling through these containers. Well, I'm doing them now on events mousewheel

and DOMMouseScroll

on the Window element that fires whenever I view the container.

But now, when I click on the scrollbar to move it, the event doesn't fire. Hence, I need an event that fires when I click on any container scroll bar in order to drag it.

window.addEventListener('DOMMouseScroll', function () {
    console.log("hello");
});
window.addEventListener('mousewheel', function () {
    console.log("hello");
});

      

DEMO

PS: I don't want to log events specifically for each container. I want to initiate these events around the world. (as I did in the above code by registering them in the window element).

+3


source to share


2 answers


You need to add a capture flag to your event listener for it to work on the "children". This flag is by default false

(docs here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener )

If true, useCapture indicates that the user wants to initiate a capture. Once capturing begins, all events of the specified type will be dispatched to the registered listener before dispatching to any EventTarget below it in the DOM tree. Events that bubble up through the tree will not trigger the listener assigned to use the capture. See DOM Level 3 Events and JavaScript Event order for detailed explanations. If not specified, useCapture defaults to false.



window.addEventListener('scroll', function () {
    console.log("hello");
}, true); // <-- the last argument is the capture argument. 

      

here is your demo changed: http://jsfiddle.net/rlemon/dq5h4kor/8/

+3


source


Are you using the jQuery 'scroll' event?

If you do

$('.parent').scroll(function() {
   //yourcode
});

      

Run on every div element:



   $('*').scroll(function() {
       //yourcode
    });

      

The above will trigger a scroll event on every scroll on every item.

It will trigger both mouse wheel scrolling and when you drag the scroll bar. JS violin

-1


source







All Articles