I have the following html code:
<input type="text" id="theInput" value=""/>
<a href="#" id="theLink">Click me</a>
I want to detect when the input changes and perform an operation in this case, but ONLY when the user has not clicked in the link. I have tried this:
$('#theLink').live('click', function(){
alert('click');
});
$('#theInput').live('change', function(){
alert('change');
});
However change
is always executed before click
when the value in the input changed, due to Javascript event precedence rules, and therefore only "change" message is displayed.
I would like it to display change
only if the input value changed and the user exited the input clicking in any other place instead of the link. In that last case I would like to display click
.
The example is here.
I use jQuery 1.6.4.
As far as I know, the click
event fires after the blur
and change
events in every browser (have a look at this JSFiddle). The order of blur
and change
is different across browsers (source: Nicholas Zakas).
To solve your problem, you could listen to click
events on the document and compare the event's target with #theLink
. Any click event will bubble up to the document (unless it is prevented).
Try this:
var lastValue = '';
$(document).click(function(event) {
var newValue = $('#theInput').val();
if ($(event.target).is('#theLink')) {
// The link was clicked
} else if (newValue !== lastValue) {
// Something else was clicked & input has changed
} else {
// Something else was clicked but input didn't change
}
lastValue = newValue;
});
JSFiddle: http://jsfiddle.net/PPvG/TTwEG/
Both events will fire but in your example the alert in the onchange
event handler fired when the onmousedown
event occurs will stop the onmouseup
event required for the onclick
event to fire. Using console.log
will show both events firing.
http://jsfiddle.net/hTqNr/4/
Ok, now i got it, you could do
$('#theLink').live('click', function(e){
alert('click');
});
$('#theInput').live('change', function(e){
//Check if the change events is triggerede by the link
if(e.originalEvent.explicitOriginalTarget.data === "Click me"){
//if this is the case trigger the click event of the link
$('#theLink').trigger("click");
}else{
//otherwise do what you would do in the change handler
alert('change');
}
});
Fiddle here http://jsfiddle.net/hTqNr/19/
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