Xander
Xander

Reputation: 407

jQuery if one statement is true and the other is not?

Right now I have a jQuery script that see's if .shipping has a descendant with a class of .sp-methods, and if it's true it will scroll down to the bottom of the page.

Current Working jQuery

if ($('.shipping .sp-methods').length > 0) {
        $('.shipping').show();
    $('html, body').animate({
        scrollTop: $(document).height() - $(window).height()
    },
    1400,
        "easeOutQuint");
}

Although what I want is the script to only run if that if that is true AND the element with an ID #shopping-cart does NOT contain the text "shipping" in it or any of its descendants. Just the text inside of something like this Shipping, not Shipping as a class or anything. Can contains do this?

I've tried this with no luck

Broken jQuery

if ($('.shipping .sp-methods').length > 0 && ! $("#shopping-cart:contains('shipping')")) {
    $('.shipping').show();
    $('html, body').animate({
        scrollTop: $(document).height() - $(window).height()
    },
    1400,
        "easeOutQuint");
}

Upvotes: 0

Views: 87

Answers (2)

strah
strah

Reputation: 6742

That's because $("somethingNonExistent") is [] (an empty array). You need to check its length in order to know if the search for your selector was successful.

Upvotes: 0

damian
damian

Reputation: 1419

You should make the second condition follow the pattern of your first. So try checking the length of the second:

EDIT: Looks like you also missed a single quote for 'shipping', updated the answer with it inserted.

if ($('.shipping .sp-methods').length > 0 && $("#shopping-cart:contains('shipping')").length <= 0) {
  $('.shipping').show();
  $('html, body').animate({
      scrollTop: $(document).height() - $(window).height()
  },
  1400,
      "easeOutQuint");
}

Upvotes: 1

Related Questions