Search code examples
javascriptjquery

jQuery - If element has class do this


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);
});

Solution

  • 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?)