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?
If you want native JS to trigger click event without clicking then use the element id and click () method of JavaScript. Create one button with “trigger” id and assign msg () function to the onClick attribute. If the button clicks then msg () function triggers a popup alert.
.click( handler )Returns: jQuery. Description: Bind an event handler to the "click". JavaScript event, or trigger that event on an element. version added: 1.0.click( handler ) handler. Type: Function( Event eventObject ) A function to execute each time the event is triggered.
Definition and Usage The click event occurs when an element is clicked. The click () method triggers the click event, or attaches a function to run when a click event occurs.
The click() method triggers the click event, or attaches a function to run when a click event occurs.
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.
You can trigger the click event on keydown using: $(this).trigger('click');
, and the preventing the default action upon keydown:
$('.custom-dropdown-btn, .custom-dropdown-btn-unfolded').keydown(function (e) {
if (e.keyCode === 13) {
$(this).trigger('click');
e.preventDefault();
}
}).click(function () {
openDropdown($(this));
});
Here's a proof-of-concept fiddle: http://jsfiddle.net/yTuR3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With