Josue Kouka

Josue Kouka

Code, Linux, and open source — one post at a time.

28 Jan 2015

Increment input value using mousewheel in javascript

We will create a project demo as follow in our www directory :

$ mkdir -p demo/static/js
$ cd demo

Create a index.html

<html>
    <head>
        <script src="static/js/jquery.min.js"></script>
        <script src="static/js/demo.js"></script>
    </head>
    <form>
        <label>Number</label>
        <input id="number" name="number" value="0" size="3" maxlength="3" type="text" max="100" min="1"/>
    </form>
</html>

NB : jQuery is required

Create a file static/js/demo.js with the code below

$('document').ready(function(){
    $('#number').bind("mousewheel", function(event, delta){
        var delta = event.originalEvent.wheelDelta;
        var self = $(this);
        var val = parseInt(self.val());
        var max = self.attr('max');
        if (delta > 0 && val < max ){
            self.val(val + 1);
        }
        else{
           if ( val > 0 ){
               self.val(val - 1);
           } 
        }
        return false;
    });
})

You can test localhost and play with your mousewheel

Voila !!!!