Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  39] [ 7]  / answers: 1 / hits: 34021  / 12 Years ago, thu, july 5, 2012, 12:00:00

I'm trying to trigger a function when a select element is changed.



Since Ipad is having trouble with on('change'), I also want to bind to 'blur', which works fine on Ipad.



However I don't want both events to trigger the function twice, so I need some kind of hook to make sure if both change and blur trigger, that the underlying function is only fired once.



This is what I'm doing now, but ... not very nice:



// make sure binding is only assigned once
var compSel = $('#my_select');
if ( compSel.jqmData('bound') != true ){
console.log(bound);
compSel.jqmData('bound', true)
.on( $.support.touch ? 'blur' : 'change', function(){
console.log(trigger);
// run function xyz
})
}


This works if you can live with all touchable devices making do with blur.



Question:

Does anyone have a better idea to make sure blur and change only trigger a function once?



Thanks for help!


More From » jquery

 Answers
21

Try creating a function, bound to both events, and adding a timeout to call the function. This way, if the function is called multiple times, it will only run once.



Something like this (you can adjust the timeout if needed):



function blurChange(e){
clearTimeout(blurChange.timeout);
blurChange.timeout = setTimeout(function(){
// Your event code goes here.
}, 100);
}

$('#my_select').on('blur change',blurChange);

[#84442] Wednesday, July 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jayla

Total Points: 14
Total Questions: 96
Total Answers: 123

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
jayla questions
;