Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On CTRL+MOUSEWHEEL event

I was asked to implement ctrl+mousewheel event for our page site in order to change image offset on user zoom in or zoom out. I found this old answer Override browsers CTRL+(WHEEL)SCROLL with javascript and I`ve tried to do the same. I downloaded the jQuery Mouse Wheel Plugin for the implementation and here is my code:

var isCtrl = false;  
       $(document).on('keydown keyup', function(e) {
            if (e.which === 17) {
                isCtrl = e.type === 'keydown' ? true : false;
            }
        }).on('mousewheel', function(e, delta) { // `delta` will be the distance that the page would have scrolled;
            // might be useful for increasing the SVG size, might not
            if (isCtrl) {
                e.preventDefault();
                alert('wheel');
            }
        });

The events works fine separately, but if I hold the CTRL button and wheel the mouse the wheel event does not fire. Does any one have better solution for this or may be I did something wrong?

like image 455
AlexBerd Avatar asked Oct 12 '15 14:10

AlexBerd


2 Answers

Fiddle, In order for it to work you have to click in the result box first before trying.

$(window).bind('mousewheel DOMMouseScroll', function(event) 
{
    if(event.ctrlKey == true)
    {
        event.preventDefault();
        if(event.originalEvent.detail > 0) {
             console.log('Down');
         }else {
             console.log('Up');
         }
    }
});
like image 165
Thaillie Avatar answered Oct 20 '22 17:10

Thaillie


To check if the ctrl key is clicked, the event already provides a way to do that. Try this:

.on('mousewheel', function(e) { 
    if (e.ctrlKey) {
        e.preventDefault();
        alert('wheel');
    }
});

This also works for e.shiftKey, e.altKey etc. I would only listen for the scroll event and there I would check if the ctrlKey is down.

like image 6
divoom12 Avatar answered Oct 20 '22 16:10

divoom12