3

I'm handling a focus event on an input and it fires an AJAX request to run $.autocomplete() with the results.

$('.section').on('focus', '#title-picker.unfetched', function(e) {
    var $titleSearch = $('[name="titlesMode"]:checked');
    var getTitles = $titleSearch.val() == "installmentTitles" ? Installment.GetAppList(selectedInstallment) : Installment.GetAllAppList();
    getTitles.done(function(result) { 
           //stuff happens here

Was focus triggered by a click in the input?

or

Was focus triggered by 'change' event attached to input[name="titlesMode"]

     }).fail(function(error){
     console.error(error);
    });        
})
.on('change', 'input[name="titlesMode"]', function() {
    $('#title-picker').addClass("unfetched");
    if ($('#title-picker').val() != '') $('#title-picker.unfetched').trigger('focus');


 });

I'm also triggering -with $.trigger('focus'), that triggers if the input has a value and fetches results again, depending on the search mode.

I just need to figure out if the focus event was triggered by a mouse clicking in the input or if it was triggered by $.trigger().

I found some code for differentiating the click event's origin but nothing for focus event :/

Any ideas?

  • just a thought. declare a global variable whose value will change on any click or any key press and also change that variable before you trigger through js. then event listener for focus and check the value of variable. – Shovan Mar 11 '14 at 16:48
  • Not sure how this is a duplicate.. the answer referred to does not work with the .on('focus') method. – Tayana Jacques Mar 13 '14 at 18:51

2 Answers2

2

It is very difficult to answer specifically without any code here. Anyhow, both the .on() and the .trigger() methods in jQuery accept a second parameter. You could use a plain object to store a variable to use to differentiate between the two cases.

References:

.trigger()

.on()

syymza
  • 679
  • 1
  • 8
  • 23
0

Try this...

 var focusType;
$(document).click(function(){
focusType = 'click';}).keyup(function(){
focusType = 'key';
});

change this variable also before you trigger focus.

Shovan
  • 185
  • 7