Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change event precedence with JQuery

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.

like image 307
Pablo Avatar asked Dec 29 '11 09:12

Pablo


3 Answers

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/

like image 105
Peter-Paul van Gemerden Avatar answered Sep 28 '22 03:09

Peter-Paul van Gemerden


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/

like image 30
Phil Parsons Avatar answered Sep 28 '22 02:09

Phil Parsons


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/

like image 45
Nicola Peluchetti Avatar answered Sep 28 '22 04:09

Nicola Peluchetti