0

I have seen some jquery code where it appears that a click event is triggered programmatically like so:

$sortElements.on('keydown', function(e) {
  if (e.which === 13 || e.which === 32) {
    e.preventDefault();
    if ($(this).is('a')) {
      e.target.click();
    } else {
      $(this).click();
    }
  }
});

Is this a best practice and or is there a better way to do this?

Also, I have read that the jquery short hand for click is deprecated and the correct way is to write:

$(elem).on("click", function(){})

I don't think it's possible to programmatically trigger a click using this new format however.

5
  • 2
    I have read that the jquery short hand for click is deprecated this is not true at all. Commented Apr 11, 2019 at 15:14
  • There is a similar shorthand for both the on and the trigger of a click, which may be confusing. You're trying to use the event listener to trigger the event. But as mentioned above, they're both still valid, so you really don't need to change anything. Commented Apr 11, 2019 at 15:16
  • $(this).is('a') => this.tagName === 'A' :| Commented Apr 11, 2019 at 15:20
  • It states that this method is deprecated as documented here. github.com/jquery/jquery-migrate/blob/master/… Commented Apr 11, 2019 at 15:24
  • That's jqMigrate, not jQuery itself Commented Apr 11, 2019 at 15:26

1 Answer 1

-4

Probably the best way to perform the click event with JQuery involved in somewhere is

$('#clickme')[0].click()
Sign up to request clarification or add additional context in comments.

8 Comments

These seems opinionated. Why would this be better than trigger('click')?
Because it has the ease of selecting the element via JQuery and the power of performing the action directly in the DOM level.
getElementById is super easy too
jQuery instantiation every time is much longer than you typing a few more characters once
I'm not addressing the OP right now, but your answer. And the point that jQuery instantiation is a much more involved process than just using a native method. While there is an ease of use of using jQuery, you should always be aware of the cost. If you are not familiar with just how much work goes into the object instantiation, I would highly recommend taking some time to review the library and just see what all goes on when one is made. It's not a simple process by far.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.