chobo2
chobo2

Reputation: 85765

Possible to bind keypress to div?

I am trying to use this plugin(a color picker). One this I don't like is that I find it hard to figure out how to close the color dialog(if it pops up - see the examples with the textboxes).

I would love to have it so that on esc is would close up the dialog. I think I would need to bind it to the div but I can't get it to work so I am not sure if it is possible.

Upvotes: 1

Views: 10896

Answers (2)

kami
kami

Reputation: 997

var listen_event = true;
$(document).bind("keydown", function(e){
    setTimeout(function(){
        if(listen_event){
            // Listen any key you need on key down
        }
    },1);
});

$("body") not always work, especialy on ajax html, so better use $(document)

timeout 1 will help you to check key or anything after generic js/html event made

hope this helps

Upvotes: 1

mattsven
mattsven

Reputation: 23263

var showing = false;

$('#colorSelector').ColorPicker({
    onShow: function (colpkr) {
        showing = true;
        return false;
    },
    onHide: function (colpkr) {
        showing = false;
        return false;
    }
});

$("body").keyup(function(e){
    if(e.keyCode == 27 && showing) $('#colorSelector').click();
    //Click it again to slide up back up, right?
});

That should work. Only thing I'm not sure about is $('#colorSelector').click();, you may need to change it to something else if that doesn't make it slide back up.

Upvotes: 2

Related Questions