MeltingDog
MeltingDog

Reputation: 15404

Anyway to use Jquery to detect if Ajax loads certain HTML?

A friend has a site on a platform where we cannot access the source code but can add our own JavaScript. Parts of the site load with Ajax.

I need to add an element when a particular piece of HTML loads. So far I've found:

$(document).ajaxComplete(function() {
   $('.booking .simple_form input[type="submit"]').hide();
   $('.booking .simple_form').append('<a id="login-btn" href="#">Login</a>');
});

But because there are 4 pieces of content loaded by Ajax on the page, this element gets appended 4 times.

I've tried wrapping that in an if statement, eg:

$(document).ajaxComplete(function() {
  if ($('#login-btn').length) {
    $('.booking .simple_form input[type="submit"]').hide();
    $('.booking .simple_form').append('<a id="login-btn" href="#">Login</a>');
  }
});

But this doesn't work - nothing appears.

Would anyone know how to I can just add 1 button?

Upvotes: 1

Views: 39

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 121998

Your condition is wrong.

if ($('#login-btn').length) {
    $('.booking .simple_form input[type="submit"]').hide();
    $('.booking .simple_form').append('<a id="login-btn" href="#">Login</a>');
  }

Should be

if (!$('#login-btn').length) {
    $('.booking .simple_form input[type="submit"]').hide();
    $('.booking .simple_form').append('<a id="login-btn" href="#">Login</a>');
  }

When there are no elements, you have to check the falsy and then enter. add ! before your condition.

Upvotes: 1

Related Questions