jQuery firing click event without a click

chaining, events, jquery

Solution

This is down to html 5 user interactions specifications. If you take a look at the HTML spec for elements with a tabIndex you'll find they mention that for any element with a tab index the enter key causes a click event.

I suspect that is what's causing this behaviour. You could try it on an older (non-html 5 compliant) browser to test whether this is the case.

Edit (as requested by poster): The answer given by @Terry provides a way to remedy the issue you're having. Using jquery's "preventDefault" on the event will stop it being hit twice when you hit enter.

Problem

Well, that's kind of what happens. ``` $('.js-custom-dropdown').find('.custom-dropdown-unfolded').toggle(); $('.custom-dropdown-btn, .custom-dropdown-btn-unfolded').keydown(function(event){ if (event.keyCode === 13) { openDropdown($(this)); } }).click( function(){ openDropdown($(this)); }); function openDropdown (element){ element.parents('.js-custom-dropdown').find('.custom-dropdown-unfolded').toggle(); console.log($(this)) } ``` When I click the dropdown button, `openDropdown` function is executed once, but when I Tab my way to the button and press enter, the function is called twice. Guess that has something to do with chaining, but I admit that I'm new to this and don't fully understand jQuery design patterns. I could of cource call the function twice in `keydown` handler and that would solve the problem, but.. you know :) Could you please explain what's wrong with the code and what causes such behavior?

Original source