Changing the priority of events using jQuery

I have the following html code:

<input type="text" id="theInput" value=""/> <a href="#" id="theLink">Click me</a> 

I want to determine when the input changes and performs the operation in this case, but ONLY when the user has not clicked the link. I tried this:

 $('#theLink').live('click', function(){ alert('click'); }); $('#theInput').live('change', function(){ alert('change'); }); 

However, change always executed before click , when the input value has changed due to Javascript event priority rules, and therefore only the message β€œchange” is displayed.

I would like it to display change only if the input value has changed and the user has exited the input by clicking anywhere else instead of the link. In this latter case, I would like to display click .

An example is here .

I am using jQuery 1.6.4.

+6
source share
4 answers

As far as I know, the click event fires after the blur and change events in each browser (see this JSFiddle ). The blur and change order is different from the browser (source: Nicholas Zakas ).

To solve your problem, you can listen to the click events in the document and compare the event target with #theLink . Any click event will depend on the document (unless this is prevented).

Try the following:

 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/

+1
source

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'); } }); 

The riddle is here http://jsfiddle.net/hTqNr/19/

+1
source

Both events will fire, but in your example, a warning in the onchange event onchange that onchange when the onmousedown event onmousedown will stop the onmouseup event needed for the onclick event to fire. Using console.log will show both events.

http://jsfiddle.net/hTqNr/4/

+1
source

why you did not select the value of the input field. you must save the initial value of the input window when ready

  initialvalue= $('#theInput').val(); 

then compare the value

  $('#theLink').live('click', function(){ var newvalue =$('#theInput').val(); if(newvalue!=initialvalue) { //do something } }); 
0
source

Source: https://habr.com/ru/post/904653/


All Articles