Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery keydown and :not with inputs

Tags:

jquery

I am using a small script that triggers the next/previous links on the page when an arrow key is pressed. I am trying to prevent this from happening when a user is typing in my search input form (maybe they spelled their query wrong and want to use the arrow keys to fix).

Here is what I'm working with:

var $j = jQuery.noConflict();

$j(function(){
    $j('.n').click(function() {
        location.href = $j(this).attr('href')
    });
    $j('.p').click(function(){
        location.href = $j(this).attr('href')
    });
});

$j(':not(input)').keydown(function(event) {
    if(event.keyCode==39) {
        $j('.n').trigger('click')
    }
    if(event.keyCode==37) {
        $j('.p').trigger('click')
    }
});

And the HTML is basically just a form with an input field. The trigger still goes even when the cursor is in the input. I'm not sure what I'm doing wrong. Any help is much appreciated!

like image 925
Adam Capriola Avatar asked Mar 15 '26 07:03

Adam Capriola


1 Answers

the event is bubbling up from the input through the rest of the document.

In your event try logging out event.trigger :

$j(':not(input)').keydown(function(event) {
  console.log(event.trigger);
  // REST OF FN

I bet it's not an HTMLInputElement

One solution, try binding on inputs and stopping the event propagation :

$j('input').keydown(function(event) {
  event.stopPropagation();
});

See if that helps.

like image 164
jesse reiss Avatar answered Mar 17 '26 21:03

jesse reiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!