I have the following code:
$('.subtle-input').live('blur', function() {
// this will fire all the time
});
$('.provider-rate-card input[type="text"]').live('change', function() {
// this will fire some of the time, only when value is changed.
});
How do I make sure that the blur
function happens before the change
function, whenever the change
function occurs?
Check out this jsfiddle :
<div class="provider-rate-card">
<input class="subtle-input" type="text" />
</div>
$(function() {
//This closure is simply here because you will be using a global variable
//It helps prevent pollution of the global namespace, which is a good
//practice in Javascript.
(function() {
//defines the flag
var changed = false;
$('.subtle-input').on('blur', function() {
blurFunction(changeFunction);
});
$('.provider-rate-card input[type="text"]').on('change', function() {
//sets the flag
changed = true;
});
function blurFunction(func) {
//do something every time it blurs
console.log('blurred');
//you will provide this callback as a parameter (see above)
return func();
}
function changeFunction() {
//checks the flag
if(changed === true) {
//do something whenever the value changes
console.log('changed');
//reset
changed = false;
}
}
})();
});
Could you just move the code into a function like so:
var doSomething = function() {
// do something
};
$('.subtle-input').live('blur', function() {
// this will fire all the time
doSomething();
});
$('.provider-rate-card input[type="text"]').live('change', function() {
// this will fire some of the time, only when value is changed.
doSomething();
});
Or in your case would the two events fire in sequence such that you wouldn't want that function to execute twice? In that case, maybe you would like to use a flag like 'charlietfl' said in the comment. Eg:
var doneSomething = false;
var doSomething = function() {
// do something
doneSomething = true;
};
$('.subtle-input').blur(function() {
// this will fire all the time
doSomething();
});
$('.provider-rate-card input[type="text"]').change(function() {
// this will fire some of the time, only when value is changed.
if (doneSomething === false) {
doSomething();
}
doneSomething = false;
});
From the comments, I did this all inside one function, manually checking the values:
$('.subtle-input').live('blur', function() {
var existing_value = $(this).data('existing_value');
var new_value = $(this).val();
if (new_value != existing_value) {
// do the change stuff
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.