Firing a dropdownlist event instantaneously (ideally jQuery)
This is related to Fire event each time a DropDownList item is selected with jQuery and How to fire an dropdownlist event instantaneously? but the answers there don't give quite what I need.
Given a dropdown selection in HTML with jQuery+JavaScript, and allowing for either mouse or keyboard interaction, I want to code such that an action will fire not just on final selection (''change'' event) but also when the user uses the keyboard up-arrow or down-arrow to change the selection without yet using the enter key to confirm that selection. In particular, in a dropdown to select color, I'd like to change the color of a swatch continually as the user arrows up or down through the options.
The following code is based in part on the discussion at Fire event each time a DropDownList item is selected with jQuery, but the "winning" version there doesn't work when keyboard is used to make selections, an开发者_开发问答d it is a pretty complete failure on Safari & Google Chrome. My code here works fine in all recent versions of Firefox, and it works fine for mouse-based actions in Chrome and Safari; however, in Chrome when the user works with the keyboard, the only event I seem to be able to capture is the ''change''; ditto for Safari, for what it's worth.
(function($) {
$.fn.dropdownSelect = function(fn) {
return this.each(function() {
// I'd expect this to be the normal case for selecting with mouse, but only seems to work in Firefox.
$('option', this).click(function() {
fn();
});
// Selection via arrow keys. Only seems to work in Firefox.
$(this).keyup(function() {
fn();
});
// Next case is crucial for Safari and Chrome, should be harmless for Firefox.
$(this).change(function() {
fn();
});
});
}
})(jQuery);
Then I invoke it like:
$('#color-dropdown').dropdownSelect(function () {
// Act on it here.
});
I tried checking also for the ''keypress'' event, but to no avail. Any ideas?
You want 'keydown'. The keypress event does not capture control functions like arrows.
精彩评论