1

I was trying to call the click event when hitting spacebar on keyboard on an anchor like so.

$("a").on("keypress", function (e) { 
    if (e.which === 32) {
        $(this).click();
        e.preventDefault();
    }
}

This does not work however. I finally figured out a fix but I don't understand why it works. The simple fix was changing $(this).click() to $(this)[0].click()

What is the [0] doing and how is it making the click event work on the anchor?

Note: I also tried $(this).trigger("click") with no luck either.

  • 1
    The `[0]` is giving you the DOM element out of the jQuery object. In fact, you shouldn't create the jQuery object to begin with since `this.click()` does the same thing. As to why it doesn't work, I don't know what *"doesn't work"* means for you. Are you trying to follow the link? Trigger another handler? Something else? –  Jan 23 '18 at 21:03
  • 2
    `$("a")` will return a collection of elements if there is more than 1, so [0] convert's it into a JS DOM object via the index access. – Sterling Archer Jan 23 '18 at 21:03
  • 3
    @SterlingArcher, that wouldn't explain the difference between `$(this).click()` and `$(this)[0].click()`, both of which reference only the currently clicked anchor. – Rick Hitchcock Jan 23 '18 at 21:07
  • 1
    Can you post your `click` event? – Rick Hitchcock Jan 23 '18 at 21:10

2 Answers2

2

See Roman Starkov's answer in the following link: Jquery how to trigger click event on href element

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();
                  ^
              Important!

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

So basically when you use the indexer you'll access the DOM's native click method instead of the jQuery implementation which does not work for links.

I wanted to mark this topic as duplicated but first I linked a wrong topic so I retracted the flag and now I cannot mark it again. So if someone has the power feel free to mark it as the duplicate of the linked topic. And if this answer helped upvote Roman Starkov's original answer in the link, he deserves it.

Wyns
  • 321
  • 1
  • 5
0

I didn't understanda exactly the scenario but that works for me, please try this:

 $('a').click(function() {
    alert('click...!');
  });

  //press enter on text area..

  $('a').keypress(function(e) {
    var key = e.which;
    console.log('checking press key: ' + key)
    if (key == 32) // the enter key code
    {
      $('a').click();

    }
  });

Feel free to rearrange...hope it helps!

Black.Jack
  • 1,878
  • 2
  • 22
  • 39