Andrew Gable
Andrew Gable

Reputation: 2752

Mouse over kineticjs rectangle event

As you can see in my fiddle. Or in my code bellow, I'm trying to get an event to happen. When hovering over the box, and clicking the space bar, the confirmation window will apear. Once clicked yes, the box will delete.

The bug/problem being that once you delete the box and click the space bar again, it comes up with the same prompt. I thought I had solved this by turning off the listening with the rTwo.setListening(false); layer.drawHit();

Anyways, any help would be appreciated. Thanks.

Code:

var stage = new Kinetic.Stage({
    container: 'container',
    width: 850,
    height: 400
});
var layer = new Kinetic.Layer();
var rTwo = new Kinetic.Rect({
    x: 0,
    y: 0,
    width: 100,
    height: 50,
    fill: 'blue',
    draggable: true,
});
layer.add(rTwo);
rTwo.on('mouseover', function() {
    document.onkeypress = function(e) {
        e = e || window.event;
        var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
        if (charCode == 32) {
            var b1 = confirm("Would you like to delete router 2?");
            if (b1 == true) {
                rTwo.hide();
                rLayer.draw();
                rTwo.setListening(false);
                rlayer.drawHit();
            } else if (b1 == false) {
                rLayer.draw();
            }
        }
    };
});
stage.add(layer);

Upvotes: 3

Views: 1061

Answers (1)

SoluableNonagon
SoluableNonagon

Reputation: 11752

http://jsfiddle.net/gSEeb/4/

So here is your logic: on mouseover you register the onkeypress function, which checks for key press and if that key is the spacebar, then show a prompt.

mouseover-> register function

function -> check key press -> is spacebar? -> show prompt

if you look at this, you check for spacebar whether you are mouseover or not, as mouseover is only registering a function. Basically you need to re-check if your mouse is in the rectangle.

 rTwo.on('mouseover mousemove', function(){
      document.onkeypress = function(e) { 
           e = e || window.event;
           var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
           if (charCode == 32 && rTwo.intersects(stage.getUserPosition())) {
                var b1 = confirm("Would you like to delete router 2?");
                if (b1 == true){
                     rTwo.hide();
                     layer.drawHit();  // or whichever layer rTwo is in
                     layer.draw();
                     rTwo.setListening(false);
                }
                else if (b1 == false){
                     layer.draw();  // you don't really need to redraw this here as nothing is changed
                }
           }
      };
 });

Upvotes: 1

Related Questions