Nick Maddren
Nick Maddren

Reputation: 661

.focusout() fires twice on second event jQuery

When I am using the .focusout() function in jQuery it seems to fire twice when I trigger the event for the second time, here is an example of my code:

$(document).ready(function() {
  var baseUrl = "http://annuityadvicecentre.dev/";
  if($('html').hasClass('ver--prize-soft')) {
    $('#home_telephone').focusout(function () {
      var softResponse = {};
      var inputVal = $(this).val();
      $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
      });
      $.ajax({
          type: 'POST',
          url: baseUrl + "lookup",
          data: {
            number: inputVal,
            phone_type: "mobile",
          },
          error: function() {
            console.log('POST Error: Mobile');
          },
      }).done(function(data) {
        // you may safely use results here
        softResponse.isMobile = data;
      });
      $.ajax({
          type: 'POST',
          url: baseUrl + "lookup",
          data: {
            number: inputVal,
            phone_type: "landline",
          },
          error: function() {
            console.log('POST Error: Landline');
          },
      }).done(function(data) {
        // you may safely use results here
        softResponse.isLandline = data;
      });
      $(document).ajaxStop(function () {
        console.log('All AJAX Requests Have Stopped');
      });
    });
  }
});

Sorry for the messy example as I have just been bootstrapping this up however you can see I am wrapping this focusout function:

$('#home_telephone').focusout(function () {...

Around my AJAX calls, now for some reason when I test this out on the page and un-focus on the #home_telephone element the .ajaxStop() function only runs once which is the functionality I want however if I then click on the element and un-focus again the .ajaxStop() function runs twice. Any idea why this might be happening? Thanks

Upvotes: 0

Views: 1427

Answers (2)

Titus
Titus

Reputation: 22484

You're adding a new ajaxStop listener every time the element is unfocused. Just move the:

$(document).ajaxStop(function () {
    console.log('All AJAX Requests Have Stopped');
});

call outside of the focusout callback function.

Upvotes: 0

Harjeet Singh
Harjeet Singh

Reputation: 396

Try to add e.stoppropogation() within function like:

$('#home_telephone').focusout(function (e) {
e.stopPropagation()();

//your code
});

Upvotes: 0

Related Questions