简体   繁体   中英

adding onMouseUp & onMousedown events — inside javascript function

I am having an div & inside it their is an input image with ID="Area-Light" .
Now here i am passing the id of the input image to a function.

I know we can directly add event handlerd inside the input tag. But i want to do it inside a javascript code.
Why the event handlers of image onMouseDown & onMouseUp are not working ?
When i press image their is no alert popup

<html>
<script type="text/javascript" src="../lib/mylib.js"></script>
<body>
        <div class="Area">
            <input id="Area-Light" type="image" src="http://www.psdgraphics.com/file/glossy-light-bulb.jpg" />
            <p class="imgtxt" ">Area-Light</p>
        <hr/>

<script type="text/javascript" >
var btn1 = new my_stateButton( "Area-Light");              // Button type
</script>

</body>
</html>

Now this function is inside mylib.js , i am adding the event handlers for onMouseDown & onMouseUp events of image :--

function my_stateButton(   canvasName )
{
    this.canvas = document.getElementById(canvasName);

    this.canvas.onmousedown = this.onMouseDown.bind(this);
    this.canvas.onmouseup = this.onMouseUp.bind(this);


    // Do some work
};

Evevnt functions :--

my_stateButton.prototype.onMouseDown = function() 
{
   alert('down');
};


my_stateButton.prototype.onMouseUp = function() 
{
   alert('up');  
};

I tried the code and it works.

The only suspicion that I have is that the " Event functions " are defined after the initialization of the my_StateButton object.

When the object is initialized, the two function ( my_stateButton.prototype.onMouseUp and my_stateButton.prototype.onMouseDown ) must be already defined, otherwise when the compiler execute the constructor code, it try to access to the bind method of undefined object and it generate a js error that block the execution of the event attaching.

You can certainly do this in javascript!

The first problem is that your script setting up btn1 is being executed before the script setting onMouseDown etc, so move it into your main script.

Next, you don't need .bind(this) . this.onMouseDown is already a function, and you're just setting the this.canvas.onmousedown property equal to that function, so just do

this.canvas.onmousedown = this.onMouseDown;

Combining those gives you a working system, as you can see in this jsbin: http://jsbin.com/pofoc/1/edit .

I'm not entirely sure why you're constructing an object to hold your canvas reference and have onMouseDown and onMouseUp properties; you could just assign them inside that function, as you'll see here: http://jsbin.com/yaqah/2/edit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM