Question

I am in a situation where I want to toggle something when the user either clicks or types enter.

Unfortunately, I'm working on a massive site which, somewhere, listens for the enter key and triggers .click() on some items when they receive an enter keyup. I can't find where, and I would not want to (or be able) to change it if I could find it, but it behaves just like this:

$("#item").on("keyup", function(event){
    if(event.keyCode == 13){$('#item').click();}
});

The result is that my "toggle" script runs twice when a user types enter, undoing itself.

$('body').on('click keyup', '#item', function(e) {
    console.log("-----------------");
    if(e.type=="click") {
        console.log("Event Type: " + e.type);
        //toggle something
    } else {
        console.log("Event Type: " + e.type+ ", keyCode: " + e.keyCode);
        //toggle something
    }
});

(Here's a JSFiddle.)

Is there a way to prevent both keyup and click from being fired when someone hits enter? The obvious answer is to remove the keyup part of the script, however, this won't work for me because the [enter] --> [click] script is not applied universally, so I need the enter key to work on the elements where it does not apply.

Was it helpful?

Solution

You could use event namespacing.

IE:

$(el).on('keyup:hamza', function(){ 
    //Detect if it was called by an element with event namespaced and do different code
})

You could also use off('keyup:hamza') to remove only your events..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top