Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  36] [ 1]  / answers: 1 / hits: 42090  / 12 Years ago, tue, june 12, 2012, 12:00:00

I have a dropdown menu that I want to connect a JQuery event to that fires if someone clicks on it but then selects the same option that is already selected.



I've got everything running using the 'change' event but there are cases where it's valid for the user to click the dropdown and reselect the same option. If that occurs I need my event handler to fire.



How can I do this?


More From » jquery

 Answers
17

Other answers do not seem to provide a solution that both handles all edge-cases (such as clicking outside of the dropdown and then clicking on it again) and/or avoids double events triggering.



The first trick is to store the value from the moment the dropdown is focused. The default change() event is used to trigger the method changewithRepeats when the dropdown value has changed, as normal.



Otherwise, a second click on the focused element will call blur(), forcing a defocus and triggering changewithRepeats if and only if the dropdown value remains the same as initially.



Opening the dropdown and cancelling out of it is not possible, this is intentional. Any defocus will call the method. All keyboard interactions also work (but the call to blur() when selecting the same value will be slightly annoying for users with screenreaders).



Focus state in the below is 0 = unfocused, 1 = when getting focus, 2 = has focus.



$(function () {
var lastFocusValue = '';
var focusState = 0;

var changeWithRepeats = function (newestValue) {
// Your change action here
};

$('select').click (function () {
if (focusState == 1) { focusState = 2; return; }
else if (focusState == 2) $(this).blur();
}).focus(function (e) {
focusState = 1;
lastFocusValue = $(this).val();
}).blur(function () {
focusState = 0;
if ($(this).val() == lastFocusValue) {
// Same value kept in dropdown
changeWithRepeats($(this).val());
}
}).change (function () {
changeWithRepeats($(this).val());
});
});


Fiddle has some more debug outputs: https://jsfiddle.net/dsschneidermann/tb5csdhp/15/


[#84960] Monday, June 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hanna

Total Points: 66
Total Questions: 99
Total Answers: 101

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;