user3086871
user3086871

Reputation: 721

How to restrict scrolling to the div that mouse is currently hovering?

I have a div name scrollable and whenever I hover mouse over it I want scrolling limited to this div only so that after reaching top/bottom of the div, scrolling will be stuck to the div. I've used the following code:

<div class="scrollable" style="overflow-y: scroll; height: 2px;" 
 onmouseover="document.body.style.overflow='hidden'" 
 onmouseout="document.body.style.overflow='auto'" >
   Some text<br>sometext<br>sometext 
</div>

Doing this gets the job done, but only problem as main scrollbar is hidden the webpage looks weird everytime I hover over '.scrollable'

Also using window.onwheel=function(){return false;} doesnt help as it prevents scrolling of anyelement.

Is there a way to enable scrolling only on hovered div and not on others while keeping main page scrollbar visible?

Thank you

Upvotes: 3

Views: 4179

Answers (2)

Haryono
Haryono

Reputation: 2812

For me, hopefully can work

        $('body').on('mousewheel', '.someDIVClass', (e: any) => {    
            if (e.originalEvent.wheelDelta / 120 > 0) {
                // You can get scroll value here to do other things
            }
            else {
                // You can get scroll value here to do  other things
            }    

            // This will prevent window to scroll
            e.preventDefault();
            e.stopPropagation();    
        });

Upvotes: 0

TheOnlyError
TheOnlyError

Reputation: 1451

You can disable scrolling without hiding the scrollbar, check this post.

Using jQuery, this would lead to:

$(".scroll").hover(function() {
  var oldScrollPos = $(window).scrollTop();

  $(window).on('scroll.scrolldisabler', function(event) {
    $(window).scrollTop(oldScrollPos);
    event.preventDefault();
  });
}, function() {
  $(window).off('scroll.scrolldisabler');
});

Check it out.

Upvotes: 4

Related Questions