简体   繁体   中英

trigger jquery key event only outside form element

Is it possible to trigger a key event only outside a form element?

Background: I have a code that loads the next page when the right key is pressed. But I don't want to trigger that event if somebody is using that key in a form element.

current code:

$(document).keydown(function(e){
    if (e.keyCode == 37) { 

        var url = $('a#left').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }

    if (e.keyCode == 39) { 

        var url = $('a#right').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }
});

Here is a basic example of the concept. Your simply adding an event handler to the document and checking that its target does not have a parent that is a form.

HTML

<form>
    Inside form
    <input/>
</form>
Outside form
<input />

Javascript

    $(document).keyup(function(event){
        if($(event.target).parents("form").length == 0){
           alert("here");
        }
    });

Working POC: http://jsfiddle.net/48NYE/

This concept can be easily applied to the script you have provided.

Modification for your Script

$(document).keydown(function(e){
    var outsideForm = $(e.target).parents("form").length == 0;
    if (e.keyCode == 37 && outsideForm) { 

        var url = $('a#left').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }

    if (e.keyCode == 39  && outsideForm){ 

        var url = $('a#right').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }
});

If you have other fields outside your form this might be quite useful I hope

LIVE DEMO

document.onkeyup = function( ev ){

  var key = ev.which || ev.keyCode ,
      aID = { 37:"left", 39:"right" }; 

  if( ! (/INPUT|TEXTAREA/i.test(ev.target)) && aID[key]) {
     var url = document.getElementById( aID[key] ).getAttribute('href');
     window.location = url;
  }

};

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