Binding mousemove within mousedown function with jQuery

14,926

.bind() and .unbind() are jQuery functions, so you need a slight adjustment , instead of this:

    sbar.bind('mousemove', function(event){
        handleMouseMove(event, sbar);
    });

You need this (wrap it as a jQuery object):

    $(sbar).bind('mousemove', function(event){
        handleMouseMove(event, sbar);
    });

The same for the .unbind():

$(sbar).unbind('mousemove');

You can see a working demo with only those corrections here :)

Share:
14,926

Related videos on Youtube

colinjwebb
Author by

colinjwebb

Updated on April 23, 2022

Comments

  • colinjwebb
    colinjwebb about 2 years

    I am trying to bind a mousemove event to a div when the left mousebutton is down, and unbind when it is released. This code should be fairly self-explainatory.

    function handleMouseDown(e, sbar){
        if (e.button == 0){
            console.log(sbar); //firebug
            sbar.bind('mousemove', function(event){
                handleMouseMove(event, sbar);
            });
        }
    }
    
    function handleMouseUp(e, sbar){
        sbar.unbind('mousemove');       
    }
    
    function handleMouseMove(e, sbar){
        // not sure it this will work yet, but unimportant
        $(".position").html(e.pageX);
    }
    
    $(document).ready(function (){
    
        var statusbar = $(".statusbar");
    
        statusbar.mousedown(function(event){
            handleMouseDown(event, this);
        });
    
        statusbar.mouseup(function(event){
            handleMouseUp(event, this);
        });
    
    });
    

    The important part of the HTML looks like this

    <div id="main">
        <div class="statusbar">
            <p class="position"></p>
        </div>
    </div>
    

    Firebug says that the bind methods are undefined on the variable sbar within handleMouseDown and handleMouseUp. The firebug console prints out <div class="statusbar"> for the line commented //firebug.

    I'm doing something wrong, probably when binding the mousedown and mouseup... but what?! I'm using jQuery v1.4.2, if that helps?

  • colinjwebb
    colinjwebb almost 14 years
    Ahh - I see. Thanks very much!
  • Nick Craver
    Nick Craver almost 14 years
    @colinjameswebb - Here's an optimized version, no need to pass sbar around, use this (the current context) to your advantage :) jsfiddle.net/JLtT3/1