156

I need an jQuery script that will see if any element has an specific class and do an action like change position.

This is the way, but I don`t think this will work.

$("a.contact").toggle(function() {
    $("#contact").animate({
        right: '0'
    }, 2000);

    if ($("#about").hasClass("opened")) {
        $("#about").animate({
            right: -700 + "px"
        }, 2000);
    }
}, function() {
    $("#contact").animate({
        right: -700 + "px"
    }, 2000);
});
2
  • Well you said that you want to know if "any" element has a certain class but your selector in your if statement is only targetting the element that has an id of "about" is that on purpose? Basically trying to figure out what your having a problem with. Also have your tried out the above code yet to see if it works? Commented Dec 30, 2010 at 18:18
  • "I don`t think this will work" How about you try it first? If it doesn't work, tell us specifically what you expect to see, and what you actually saw. Commented Dec 30, 2010 at 18:25

2 Answers 2

283

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to check for only one class you can use this:

if ($("#about").hasClass("opened")) {
    // ...
}

And if you want to check for some classes you can use this:

if ($("#about").is(".opended, .class-name1, class-name2")) {
    // ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.